📌  相关文章
📜  Python - 具有相同索引的元素

📅  最后修改于: 2022-05-13 01:54:57.333000             🧑  作者: Mango

Python - 具有相同索引的元素

给定一个列表,获取所有处于其索引值的元素。

方法#1:使用循环

在此,我们检查每个元素,如果它等于其索引,则将其添加到结果列表中。

Python3
# Python3 code to demonstrate working of 
# Elements with same index
# Using loop
  
# initializing list
test_list = [3, 1, 2, 5, 4, 10, 6, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# enumerate to get index and element
res = []
for idx, ele in enumerate(test_list):
    if idx == ele:
        res.append(ele)
  
# printing result 
print("Filtered elements : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Elements with same index
# Using list comprehension + enumerate()
  
# initializing list
test_list = [3, 1, 2, 5, 4, 10, 6, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# enumerate to get index and element
res = [ele for idx, ele in enumerate(test_list) if idx == ele]
  
# printing result 
print("Filtered elements : " + str(res))


输出
The original list is : [3, 1, 2, 5, 4, 10, 6, 9]
Filtered elements : [1, 2, 4, 6]

方法 #2:使用列表理解+ enumerate()

在这里,我们执行与上述方法类似的函数,改变的是我们使用列表理解来使解决方案紧凑。

蟒蛇3

# Python3 code to demonstrate working of 
# Elements with same index
# Using list comprehension + enumerate()
  
# initializing list
test_list = [3, 1, 2, 5, 4, 10, 6, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# enumerate to get index and element
res = [ele for idx, ele in enumerate(test_list) if idx == ele]
  
# printing result 
print("Filtered elements : " + str(res))
输出
The original list is : [3, 1, 2, 5, 4, 10, 6, 9]
Filtered elements : [1, 2, 4, 6]