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]
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With