我有一个索引列表,例如:
b=[0,2]
和元素列表:
a = ['elem0','elem1','elem2']
我需要一个由a
中的元素组成的列表,其中的索引位于b
中
(在此示例中为:['elem0','elem2']
)
答案 0 :(得分:8)
[a[i] for i in b]
答案 1 :(得分:1)
或者:
from operator import itemgetter
b=[0,2]
a = ['elem0','elem1','elem2']
print itemgetter(*b)(a)
>>> ('elem0','elem2')
答案 2 :(得分:0)
使用列表推导将索引映射到列表:
b=[0,2]
a = ['elem0','elem1','elem2']
sublist = [a[i] for i in b]
答案 3 :(得分:0)
>ipython
In [1]: b=[0,2]
In [2]: a = ['elem0','elem1','elem2']
In [3]: [a[i] for i in b]
Out[3]: ['elem0', 'elem2']
如果您不了解它们,请在python手册中查找“list comprehensions”。