如果要尝试在列表中查找项目的索引,您可以通过几种不同的方式来完成,这是我所知道的最快的方式:
aList = [123, 'xyz', 'zara','xyz', 'abc'];
indices = [i for i, x in enumerate(aList) if x == "xyz"]
print(indices)
另一种不是 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)
第一种方法无疑更快,但是如果你想更快,有什么办法吗?对于第一个索引使用方法:
aList = [123, 'xyz', 'zara','xyz', 'abc'];
print "Index for xyz : ", aList.index( 'xyz' )
速度非常快,但不能处理多个索引。
如何才能加快速度?
最佳答案
使用 list.index(elem, start)
!它在 C 中使用了一个 for
循环(请参阅 CPython 的 listobject.c 源代码中的实现 list_index_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))
关于python - 在列表中查找项目索引的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35640780/