在列表中查找项目索引的最快方法? [英] Fastest way to find Indexes of item in list?

查看:82
本文介绍了在列表中查找项目索引的最快方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果要尝试在列表中查找项目的索引,您可以通过以下几种不同的方式来完成,这是我所知道的最快的方法:

If one was to attempt to find the indexes of an item in a list you could do it a couple different ways here is what I know to be the fastest:

aList = [123, 'xyz', 'zara','xyz', 'abc']; 
indices = [i for i, x in enumerate(aList) if x == "xyz"]
print(indices)

另一种非pythonic且速度较慢的方法:

Another way not pythonic and slower:

count = 0
indices = []
aList = [123, 'xyz', 'zara','xyz', 'abc'];
for i in range(0,len(aList):
    if 'xyz' == aList[i]:
        indices.append(i)
print(indices)

第一种方法无疑更快,但是如果你想更快怎么办,有没有办法?对于第一个索引使用方法:

The first method is undoubtedly faster however what if you wanted to go faster, is there a way? For the first index using method:

aList = [123, 'xyz', 'zara','xyz', 'abc'];             
print "Index for xyz : ", aList.index( 'xyz' ) 

速度很快,但不能处理多个索引.
如何加快速度?

is very fast but can't handle multiple indexes.
How might one go about speeding things up?

推荐答案

def find(target, myList):
    for i in range(len(myList)):
        if myList[i] == target:
            yield i

def find_with_list(myList, target):
     inds = []
     for i in range(len(myList)):
         if myList[i] == target:
             inds += i,
     return inds


In [8]: x = range(50)*200
In [9]: %timeit [i for i,j in enumerate(x) if j == 3]
1000 loops, best of 3: 598 us per loop

In [10]: %timeit list(find(3,x))
1000 loops, best of 3: 607 us per loop
In [11]: %timeit find(3,x)
1000000 loops, best of 3: 375 ns per loop

In [55]: %timeit find_with_list(x,3)
1000 loops, best of 3: 618 us per loop

假设您想要一个列表作为输出:

Assuming you want a list as your output:

  • 在我的测试中,所有选项似乎都表现出相似的时间性能,列表理解是最快的(勉强).

如果使用生成器是可以接受的,那么它比其他方法要快得多.虽然它不考虑实际迭代索引,也不存储它们,所以索引不能重复第二次.

If using a generator is acceptable, it's way faster than the other approaches. Though it doesn't account for actually iterating over the indices, nor does it store them, so the indices cannot be iterated over a second time.

这篇关于在列表中查找项目索引的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆