如何在Python中使用索引从列表中提取元素?
如果你在Python中有一个列表,想要把索引为1、2和5的元素提取到一个新的列表里,你会怎么做呢?
我这样做了,但不是很满意:
>>> a
[10, 11, 12, 13, 14, 15]
>>> [x[1] for x in enumerate(a) if x[0] in [1,2,5]]
[11, 12, 15]
有没有更好的方法呢?
更一般来说,给定一个索引的元组,你会怎么用这个元组从列表中提取对应的元素,甚至是重复的元素(比如元组 (1,1,2,1,5)
会得到 [11,11,12,11,15]
)。
5 个回答
6
试试看
numbers = range(10, 16)
indices = (1, 1, 2, 1, 5)
result = [numbers[i] for i in indices]
10
我觉得你在找这个:
elements = [10, 11, 12, 13, 14, 15]
indices = (1,1,2,1,5)
result_list = [elements[i] for i in indices]
91
也许可以用这个:
[a[i] for i in (1,2,5)]
# [11, 12, 15]