所以想象一下,我想在另一个列表中找到第二,第三和第四个元素。在For循环中查找列表中的第N个元素
position = [2,3,4]
Sample_List = ['a','b','c','d','e']
环路会给后面的结果:
['c','d','e']
所以想象一下,我想在另一个列表中找到第二,第三和第四个元素。在For循环中查找列表中的第N个元素
position = [2,3,4]
Sample_List = ['a','b','c','d','e']
环路会给后面的结果:
['c','d','e']
简单:
the_elements = [Sample_List[i] for i in position]
您还可以使用
elements = map(lambda k:Sample_List[k], position)
在python3你需要将其转换为列表
elements = list(map(lambda k:Sample_List[k], position))
使用operator.itemgetter
另一种方法:对于i在位置
>>> from operator import itemgetter
>>> position = [2,3,4]
>>> Sample_List = ['a','b','c','d','e']
>>> itemgetter(*position)(Sample_List)
('c','d','e')
':打印sample_list [I]'或'[sample_list []对于i在位置i]' – NightShadeQueen
'地图(Sample_List .__ getitem__,位置)' –