Python - 具有相同索引的元素
给定一个列表,获取所有处于其索引值的元素。
Input : test_list = [3, 1, 8, 5, 4, 10, 6, 9]
Output : [1, 4, 6]
Explanation : These elements are at same position as its number.
Input : test_list = [3, 10, 8, 5, 14, 10, 16, 9]
Output : []
Explanation : No number at its index.
方法#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]