python - Access multiple elements of list knowing their index -


i need choose elements given list, knowing index. let create new list, contains element index 1, 2, 5, given list [-2, 1, 5, 3, 8, 5, 6]. did is:

a = [-2,1,5,3,8,5,6] b = [1,2,5] c = [ a[i] in b] 

is there better way it? c = a[b] ?

you can use operator.itemgetter:

>>> operator import itemgetter  >>> = [-2, 1, 5, 3, 8, 5, 6] >>> b = [1, 2, 5] >>> print itemgetter(*b)(a) (1, 5, 5) 

or can use numpy:

>>> import numpy np >>> = np.array([-2, 1, 5, 3, 8, 5, 6]) >>> b = [1, 2, 5] >>> print list(a[b]) [1, 5, 5] 

but really, current solution fine. it's neatest out of of them.


Comments