python在给定索引的列表中查找项目

时间:2013-01-31 15:49:50

标签: python list

是否还有其他更快捷的方法可以在索引位置查找项目。

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

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

1 个答案:

答案 0 :(得分:7)

如果您反复使用相同的索引,那么使用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']