Access multiple elements of list knowing their index
You can use operator.itemgetter
:
from operator import itemgetter a = [-2, 1, 5, 3, 8, 5, 6]b = [1, 2, 5]print(itemgetter(*b)(a))# Result:(1, 5, 5)
Or you can use numpy:
import numpy as npa = np.array([-2, 1, 5, 3, 8, 5, 6])b = [1, 2, 5]print(list(a[b]))# Result:[1, 5, 5]
But really, your current solution is fine. It's probably the neatest out of all of them.
Alternatives:
>>> map(a.__getitem__, b)[1, 5, 5]
>>> import operator>>> operator.itemgetter(*b)(a)(1, 5, 5)
Another solution could be via pandas Series:
import pandas as pda = pd.Series([-2, 1, 5, 3, 8, 5, 6])b = [1, 2, 5]c = a[b]
You can then convert c back to a list if you want:
c = list(c)