Python最快的方法来查找列表中项目的索引

Tyl*_*wan 2 python indexing performance list

如果一个人想要在列表中找到项目的索引,你可以用两种不同的方式来做这就是我所知道的最快的

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

另一种方式不是pythonic和慢

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)
Run Code Online (Sandbox Code Playgroud)

第一种方法无疑是更快但是如果你想要更快的话有什么方法呢?对于第一个索引使用方法

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

是非常快但无法处理多个索引如何加快速度?

Gar*_*t R 5

    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
Run Code Online (Sandbox Code Playgroud)

假设您想要一个列表作为输出:所有选项似乎都表现出与我的测试类似的时间性能,列表理解是最快的(几乎没有).

如果你回归发电机很酷,那么它比其他方法更快.认为它不考虑实际迭代索引,也不存储它们,因此inds不能再次迭代.

  • `[i for i,j in enumerate(x)if x == 3]`,second`x`应该是`j`. (2认同)
  • 你的最后两个例子更快,因为你没有消耗生成器...... (2认同)

小智 5

使用list.index(elem, start)!这在C语言中使用了for循环(请参见list_index_implCPython的listobject.c的源代码中的实现函数)。避免循环遍历Python中的所有元素,它比C中的慢。

def index_finder(lst, item):
    """A generator function, if you might not need all the indices"""
    start = 0
    while True:
        try:
            start = lst.index(item, start)
            yield start
            start += 1
        except ValueError:
            break

import array
def index_find_all(lst, item, results=None):
    """If you want all the indices.
    Pass results=[] if you explicitly need a list,
    or anything that can .append(..)"""
    if results is None:
        length = len(lst)
        results = array.array('B') if length <= 2**8 else array.array('H') if length <= 2**16 else array.array('L') if length <= 2**32 else array.array('Q')
    start = 0
    while True:
        try:
            start = lst.index(item, start)
            results.append(start)
            start += 1
        except ValueError:
            return results

# Usage example
l = [1, 2, 3, 4, 5, 6, 7, 8] * 32

print(*index_finder(l, 1))
print(*index_find_all(l, 1))
Run Code Online (Sandbox Code Playgroud)