hoang tran - 11 months ago 74

Python Question

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:

`a = [-2,1,5,3,8,5,6]`

b = [1,2,5]

c = [ a[i] for i in b]

Is there any better way to do it? something like c = a[b] ?

Answer

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)
(1, 5, 5)
```

Or you can use numpy:

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

But really, your current solution is fine. It's probably the neatest out of all of them.

Source (Stackoverflow)