Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest and most efficient function to return a sublist based on an index list?

Tags:

python

list

Say I have a list l:

['a','b','c','d','e']

and a list of indexes idx:

[1,3]

What is the simplest and most efficient function that will return:

['b','d']
like image 418
Hailiang Zhang Avatar asked Nov 29 '25 06:11

Hailiang Zhang


2 Answers

Try using this:

[l[i] for i in idx]
like image 125
arshajii Avatar answered Nov 30 '25 21:11

arshajii


You want operator.itemgetter.

In my first example, I'll show how you can use itemgetter to construct a callable which you can use on any indexable object:

from operator import itemgetter
items = itemgetter(1,3)
items(yourlist)  #('b', 'd')

Now I'll show how you can use argument unpacking to store your indices as a list

from operator import itemgetter
a = ['a','b','c','d','e']
idx = [1,3]
items = itemgetter(*idx)
print items(a)  #('b', 'd')

Of course, this gives you a tuple, not a list, but it's trivial to construct a list from a tuple if you really need to.

like image 24
mgilson Avatar answered Nov 30 '25 19:11

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!