3

有没有其他更快的方法可以在索引位置找到项目。

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

My way: 
[items[i] for i in indices]
4

1 回答 1

8

如果您一遍又一遍地使用相同的索引,您可能会做得更好operator.itemgetter

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

根据我的简单基准,itemgetter大约快 2.5 倍(但我没有计算实际构造getter函数开始所需的时间)。

>>> 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']
于 2013-01-31T15:51:49.203 回答