Python – 查找第 K 个偶数元素
给定一个列表,提取第 K 次出现的偶数元素。
Input : test_list = [4, 6, 2, 3, 8, 9, 10, 11], K = 3
Output : 8
Explanation : K = 3, i.e 0 based index, 4, 6, 2 and 4th is 8.
Input : test_list = [4, 6, 2, 3, 8, 9, 10, 11], K = 2
Output : 2
Explanation : K = 2, i.e 0 based index, 4, 6, and 3rd is 2.
方法#1:使用列表推导
在此,我们使用 %运算符提取偶数元素列表,并使用列表索引访问来获取第 K 个偶数元素。
Python3
# Python3 code to demonstrate working of
# Kth Even Element
# Using list comprehension
# initializing list
test_list = [4, 6, 2, 3, 8, 9, 10, 11]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# list comprehension to perform iteration and % 2 check
res = [ele for ele in test_list if ele % 2 == 0][K]
# printing result
print("The Kth Even Number : " + str(res))
Python3
# Python3 code to demonstrate working of
# Kth Even Element
# Using filter() + lambda
# initializing list
test_list = [4, 6, 2, 3, 8, 9, 10, 11]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# list comprehension to perform iteration and % 2 check
res = list(filter(lambda ele : ele % 2 == 0, test_list))[K]
# printing result
print("The Kth Even Number : " + str(res))
输出
The original list is : [4, 6, 2, 3, 8, 9, 10, 11]
The Kth Even Number : 10
方法 #2:使用 filter() + lambda
在此,查找偶数元素的任务是使用 filter() + lambda 函数完成的。
Python3
# Python3 code to demonstrate working of
# Kth Even Element
# Using filter() + lambda
# initializing list
test_list = [4, 6, 2, 3, 8, 9, 10, 11]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 4
# list comprehension to perform iteration and % 2 check
res = list(filter(lambda ele : ele % 2 == 0, test_list))[K]
# printing result
print("The Kth Even Number : " + str(res))
输出
The original list is : [4, 6, 2, 3, 8, 9, 10, 11]
The Kth Even Number : 10