[英]Finding Nth element in a list using For Loop
所以我想在另一個列表中找到第2,第3和第4個元素。
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
方法:
>>> from operator import itemgetter
>>> position = [2,3,4]
>>> Sample_List = ['a','b','c','d','e']
>>> itemgetter(*position)(Sample_List)
('c','d','e')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.