[英]Python: How to get the nth element from list, where n is from a list
所以說我有:
a = ['the dog', 'cat', 'the frog went', '3452', 'empty', 'animal']
b = [0, 2, 4]
我如何退貨:
c = ['the dog', 'the frog went', 'empty'] ?
即我如何從a返回第n個元素,其中n包含在單獨的列表中?
使用列表推導,只需執行以下操作:
c = [a[x] for x in b]
另一種方法是:
map(a.__getitem__, b)
還有另一種解決方案:如果您願意使用numpy( import numpy as np
),則可以使用其精美的索引功能(如Matlab),即在一行中:
c = list(np.array(a)[b])
其他選項,名單理解迭代a
替代(低效率):
[ e for i, e in enumerate(a) if i in b ]
#=> ['the dog', 'the frog went', 'empty']
帶lambda
O:
map( lambda x: a[x], b )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.