Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python find items in a list given indices

Tags:

python

list

Is there any other FASTER way to find the items at index locations.

items = ['aaa','sss','ddd','fff','gggg','hhhh']
indices = [1,3,4]

My way: 
[items[i] for i in indices]
like image 994
user1140126 Avatar asked Dec 20 '25 09:12

user1140126


1 Answers

If you're using the same indices over and over, you might do better with operator.itemgetter:

getter = itemgetter(1,3,4)
desired = getter(items)

According to my simple benchmark, itemgetter is about 2.5x faster (but I didn't time how long it takes to actually construct the getter function to begin with).

>>> items = ['aaa','sss','ddd','fff','gggg','hhhh']
>>> indices = [1,3,4]
>>> from operator import itemgetter
>>> import timeit
>>> getter = itemgetter(*indices)
>>> def list_comp(items=items,indices=indices):
...     return [items[i] for i in indices]
... 
>>> timeit.timeit('getter(items)','from __main__ import getter,items')
0.2926821708679199
>>> timeit.timeit('list_comp()','from __main__ import list_comp')
0.7736802101135254
>>> getter(items)
('sss', 'fff', 'gggg')
>>> list_comp()
['sss', 'fff', 'gggg']
like image 66
mgilson Avatar answered Dec 23 '25 00:12

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!