[英]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.