繁体   English   中英

Python:如何从列表中获取第n个元素,其中n从列表中获取

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM