Reputation: 473
So say I have:
a = ['the dog', 'cat', 'the frog went', '3452', 'empty', 'animal']
b = [0, 2, 4]
How can I return:
c = ['the dog', 'the frog went', 'empty'] ?
i.e how can I return the nth element from a, where n is contained in a separate list?
Upvotes: 1
Views: 2705
Reputation: 11183
Other option, list comprehension iterating over a
instead (less efficient):
[ e for i, e in enumerate(a) if i in b ]
#=> ['the dog', 'the frog went', 'empty']
O with lambda
:
map( lambda x: a[x], b )
Upvotes: 0
Reputation: 2364
Yet another solution: if you are willing to use numpy (import numpy as np
), you could use its fancy indexing feature (à la Matlab), that is, in one line:
c = list(np.array(a)[b])
Upvotes: 0