I need to choose some elements from the given list, knowing their index. Let say I would like to create a new list, which contains element with index 1, 2, 5, from given list [-2, 1, 5, 3, 8, 5, 6]. What I did is:
JavaScript
x
4
1
a = [-2,1,5,3,8,5,6]
2
b = [1,2,5]
3
c = [ a[i] for i in b]
4
Is there any better way to do it? something like c = a[b] ?
Advertisement
Answer
You can use operator.itemgetter
:
JavaScript
1
7
1
from operator import itemgetter
2
a = [-2, 1, 5, 3, 8, 5, 6]
3
b = [1, 2, 5]
4
print(itemgetter(*b)(a))
5
# Result:
6
(1, 5, 5)
7
Or you can use numpy:
JavaScript
1
7
1
import numpy as np
2
a = np.array([-2, 1, 5, 3, 8, 5, 6])
3
b = [1, 2, 5]
4
print(list(a[b]))
5
# Result:
6
[1, 5, 5]
7
But really, your current solution is fine. It’s probably the neatest out of all of them.