为什么我的代码如此缓慢(低效)?我需要制作两种方法来记录处理给定大小的列表所需的时间。我有一个 search_fast
和 search_slow
方法。即使这两个搜索时间之间存在差异。 Search_fast
仍然很慢。我想优化处理时间,而不是使用 search_fast
获取 8.99038815498
和使用 search_slow
获取 65.0739619732
。只需要几分之一秒。我能做些什么?我将永远感激一些提示,因为编码对我来说仍然很新。 :)
from timeit import Timer
def fillList(l, n):
l.extend(range(1, n + 1))
l = []
fillList(l, 100)
def search_fast(l):
for item in l:
if item == 10:
return True
return False
def search_slow(l):
return_value = False
for item in l:
if item == 10:
return_value = True
return return_value
t = Timer(lambda: search_fast(l))
print t.timeit()
t = Timer(lambda: search_slow(l))
print t.timeit()
最佳答案
最快的方法是使用 in
运算符,它测试序列中值的成员资格。
if value in some_container:
…
引用:https://docs.python.org/3/reference/expressions.html#membership-test-operations
更新:另外,如果您经常需要测试成员资格,请考虑使用集合而不是列表。
可以在这里找到一些优缺点:https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset
关于python - 列表处理时间慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37530819/