Reputation: 5084
I have a list of indices, something like:
b=[0,2]
and a list of elements:
a = ['elem0','elem1','elem2']
I need a list that is composed of the elements in a
with the indices in b
(in this example: ['elem0','elem2']
)
Upvotes: 2
Views: 257
Reputation: 29093
Or:
from operator import itemgetter
b=[0,2]
a = ['elem0','elem1','elem2']
print itemgetter(*b)(a)
>>> ('elem0','elem2')
Upvotes: 1
Reputation: 2248
>ipython
In [1]: b=[0,2]
In [2]: a = ['elem0','elem1','elem2']
In [3]: [a[i] for i in b]
Out[3]: ['elem0', 'elem2']
Look up "list comprehensions" in the python manual if you don't know them.
Upvotes: 0
Reputation: 46183
Use a list comprehension to map the indexes to the list:
b=[0,2]
a = ['elem0','elem1','elem2']
sublist = [a[i] for i in b]
Upvotes: 0