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?
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?
An other way is :
map(a.__getitem__, b)
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])
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 )