Python – 从列表中获取偶数元素的索引
有时,在使用Python列表时,我们可能会遇到希望找到偶数元素的问题。此任务可能发生在许多领域,例如 Web 开发和使用数据库时。我们有时可能只需要找到它们的索引。让我们讨论一些查找偶数元素索引的方法。
方法#1:使用循环
这是可以执行此任务的蛮力方法。在此,我们检查列表中的偶数元素并相应地附加其索引。
# Python3 code to demonstrate working of
# Even Elements indices
# using loop
# initialize list
test_list = [5, 6, 10, 4, 7, 1, 19]
# printing original list
print("The original list is : " + str(test_list))
# Even Elements indices
# using loop
res = []
for idx, ele in enumerate(test_list):
if ele % 2 == 0:
res.append(idx)
# printing result
print("Indices list Even elements is : " + str(res))
输出 :
The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list Even elements is : [1, 2, 3]
方法#2:使用列表推导
这是可以执行此任务的简写。此方法的工作方式与上述方法类似。不同之处在于它是单线。
# Python3 code to demonstrate working of
# Even Elements indices
# using list comprehension
# initialize list
test_list = [5, 6, 10, 4, 7, 1, 19]
# printing original list
print("The original list is : " + str(test_list))
# Even Elements indices
# using list comprehension
res = [idx for idx, ele in enumerate(test_list) if ele % 2 == 0]
# printing result
print("Indices list Even elements is : " + str(res))
输出 :
The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list Even elements is : [1, 2, 3]