Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找列表中项目索引的最快方法?_Python_Performance_List_Indexing - Fatal编程技术网

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

Python 查找列表中项目索引的最快方法?,python,performance,list,indexing,Python,Performance,List,Indexing,如果要尝试在列表中查找某个项目的索引,您可以使用几种不同的方法,我知道这是最快的方法: aList = [123, 'xyz', 'zara','xyz', 'abc']; indices = [i for i, x in enumerate(aList) if x == "xyz"] print(indices) 另一种方式不是肾盂式的,速度较慢: count = 0 indices = [] aList = [123, 'xyz', 'zara','xyz', 'ab

如果要尝试在列表中查找某个项目的索引,您可以使用几种不同的方法,我知道这是最快的方法:

aList = [123, 'xyz', 'zara','xyz', 'abc']; 
indices = [i for i, x in enumerate(aList) if x == "xyz"]
print(indices)
另一种方式不是肾盂式的,速度较慢:

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)
第一种方法无疑更快,但是如果你想走得更快,有办法吗?对于使用方法的第一个索引:

aList = [123, 'xyz', 'zara','xyz', 'abc'];             
print "Index for xyz : ", aList.index( 'xyz' ) 
非常快,但无法处理多个索引。
一个人怎样才能加快速度呢

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
假设您想要一个列表作为输出:

  • 对于我的测试,所有选项似乎都表现出相似的时间性能,列表理解速度最快(几乎没有)
如果使用生成器是可以接受的,那么它比其他方法快得多。虽然它不考虑实际迭代索引,也不存储它们,所以索引不能再迭代一次

D=dict()
for i, item in enumerate(l):
    if item not in D:
        D[item] = [i]
    else:
        D[item].append(i)
然后只需调用D[item]即可获得匹配的索引。您将放弃初始计算时间,但在调用时间内获得它。

使用
list.index(elem,start)
!在C中为循环使用
(参见CPython源代码中的实现
list\u index\u impl
函数)。 避免在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))
def索引查找器(lst,项目):
“”“生成器函数,如果您可能不需要所有索引”“”
开始=0
尽管如此:
尝试:
开始=第一索引(项目,开始)
产量起点
开始+=1
除值错误外:
打破
导入数组
def index_find_all(lst,项目,结果=无):
“”“如果需要所有索引。
传递结果=[]如果您明确需要一个列表,
或者任何可以添加的内容。附加(…)
"""
如果结果为无:
长度=长度(lst)

结果=(array.array('B')如果长度要获取项的索引,可以使用字典

aList = [123, 'xyz', 'zara','xyz', 'abc'];
#The following apporach works only on lists with unique values
aList = list(np.unique(aList)); 
dict = enumerate(aList);
# get inverse mapping of above dictionary, replace key with values
inv_dict = dict(zip(dict.values(),dict.keys()))
# to get index of item by value, use 'inv_dict' and to get value by index, use 'dict'
valueofItemAtIndex0 = dict[0]; # value = 123
indexofItemWithValue123 = inv_dict[123]; # index = 0

我使用另一种方法在Python 3中查找列表中元素的索引:

def index_of(elem, a):
    a_e = enumerate(a)
    a_f = list(filter(lambda x: x[1] == elem, a_e))
    if a_f:
        return a_f[0][0]
    else:
        return -1
一些测试:

a=[1,2,3,4,2]
index_of(2,a)

此函数始终返回元素的第一次出现。如果元素不在列表中,则返回-1。对于我的目标,该解决方案运行良好。

只需使用zip从项目列表创建项目->索引字典,如下所示:

items_as_dict = dict(zip(list_of_items,range(0,len(list_of_items))))
index = items_as_dict(item)

所以你说的是迭代每个索引并进行直接比较,这是获取列表中匹配项的所有索引位置的最快方法?这是我知道的假设串行计算的最快方法。如果它是一个巨大的列表,你可以将其拆分并并行处理部分,这可能会更快
[i for i,j in enumerate(x)如果x==3]
,第二个
x
应该是
j
@GarrettR我在想并行可能是一种像分而治之的方法,我必须研究一下。一定有更好的方法。@gill哇!这是一个巨大的错误,而且很有意义,为什么它很慢。我修复了代码和结果。谢谢!