Python|通过索引查找列表的元素
给定两个带有元素和索引的列表,编写一个Python程序以在列表 2中存在的索引处查找列表 1的元素。
例子:
Input : lst1 = [10, 20, 30, 40, 50]
lst2 = [0, 2, 4]
Output : [10, 30, 50]
Explanation:
Output elements at indices 0, 2 and 4 i.e 10, 30 and 50 respectively.
Input : lst1 = ['Hello', 'geeks', 'for', 'geeks']
lst2 = [1, 2, 3]
Output : ['geeks', 'for', 'geeks']
以下是完成上述任务的一些 Pythonic 方法。
方法#1:朴素(列表理解)
查找所需元素的第一种方法是使用列表推导。我们遍历“lst2”,对于每个第 i个元素,我们输出 lst1[i]。
# Python3 program to Find elements of a
# list by indices present in another list
def findElements(lst1, lst2):
return [lst1[i] for i in lst2]
# Driver code
lst1 = [10, 20, 30, 40, 50]
lst2 = [0, 2, 4]
print(findElements(lst1, lst2))
输出:
[10, 30, 50]
方法 #2:使用Python map()
我们还可以使用Python map()
方法,在 lst2 上应用lst1.__getitem__
函数,该函数为lst2的每个元素“i”返回lst1[i]
。
# Python3 program to Find elements of a
# list by indices present in another list
def findElements(lst1, lst2):
return list(map(lst1.__getitem__, lst2))
# Driver code
lst1 = [10, 20, 30, 40, 50]
lst2 = [0, 2, 4]
print(findElements(lst1, lst2))
输出:
[10, 30, 50]
方法 #3:使用itemgetter()
# Python3 program to Find elements of a
# list by indices present in another list
from operator import itemgetter
def findElements(lst1, lst2):
return list((itemgetter(*lst2)(lst1)))
# Driver code
lst1 = [10, 20, 30, 40, 50]
lst2 = [0, 2, 4]
print(findElements(lst1, lst2))
输出:
[10, 30, 50]
方法 #4:使用numpy
# Python3 program to Find elements of a
# list by indices present in another list
import numpy as np
def findElements(lst1, lst2):
return list(np.array(lst1)[lst2])
# Driver code
lst1 = [10, 20, 30, 40, 50]
lst2 = [0, 2, 4]
print(findElements(lst1, lst2))
输出:
[10, 30, 50]