Python - 查找列表中第一个和最后一个偶数元素之间的距离
给定一个列表,编写一个Python程序来查找列表中偶数元素的跨度,即偶数元素第一次和最后一次出现之间的距离。
例子:
Input : test_list = [1, 3, 7, 4, 7, 2, 9, 1, 10, 11]
Output : 5
Explanation : Even elements begin at 4 and end at 10, spanning 5 indices.
Input : test_list = [1, 3, 7, 4, 7, 2, 9, 1, 1, 11]
Output : 2
Explanation : Even elements begin at 4 and end at 2, spanning 2 indices.
方法#1:使用列表理解
在这里,我们使用列表理解获得所有偶数元素的所有索引,然后执行列表中匹配元素的第一个和最后一个索引的差异。
Python3
# Python3 code to demonstrate working of
# Even elements span in list
# Using list comprehension
# initializing Matrix
test_list = [1, 3, 7, 4, 7, 2, 9, 1, 10, 11]
# printing original list
print("The original list is : " + str(test_list))
# getting even indices
indices_list = [idx for idx in range(
len(test_list)) if test_list[idx] % 2 == 0]
# getting difference of first and last occurrence
res = indices_list[-1] - indices_list[0]
# printing result
print("Even elements span : " + str(res))
Python3
# Python3 code to demonstrate working of
# Even elements span in list
# Using filter() + lambda
# initializing Matrix
test_list = [1, 3, 7, 4, 7, 2, 9, 1, 10, 11]
# printing original list
print("The original list is : " + str(test_list))
# getting even indices
indices_list = list(
filter(lambda x: test_list[x] % 2 == 0, range(len(test_list))))
# getting difference of first and last occurrence
res = indices_list[-1] - indices_list[0]
# printing result
print("Even elements span : " + str(res))
输出
The original list is : [1, 3, 7, 4, 7, 2, 9, 1, 10, 11]
Even elements span : 5
方法 #2:使用filter() + lambda
在这里,我们使用 filter() 和 lambda 执行获取元素索引的任务。
蟒蛇3
# Python3 code to demonstrate working of
# Even elements span in list
# Using filter() + lambda
# initializing Matrix
test_list = [1, 3, 7, 4, 7, 2, 9, 1, 10, 11]
# printing original list
print("The original list is : " + str(test_list))
# getting even indices
indices_list = list(
filter(lambda x: test_list[x] % 2 == 0, range(len(test_list))))
# getting difference of first and last occurrence
res = indices_list[-1] - indices_list[0]
# printing result
print("Even elements span : " + str(res))
输出
The original list is : [1, 3, 7, 4, 7, 2, 9, 1, 10, 11]
Even elements span : 5