python - 列表处理时间慢

标签 python list for-loop timeit

为什么我的代码如此缓慢(低效)?我需要制作两种方法来记录处理给定大小的列表所需的时间。我有一个 search_fastsearch_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/

相关文章:

javascript - 将 HTML 元素推送到一个数组中,稍后将它们追加到一个 div 中,该 div 也是动态创建的

java - 如何让我的文字之一垂直打印?

python - 使用 Tensorflow Keras 将 CNN 与 LSTM 相结合

python - 如何从 python 中的 raw_input 制作列表?

C# list<string> in a list<string>[] .toList()

python - 在python中有效地获取未排序列表中的第k个最小元素

python - 如何从 Python 列表中删除元素的所有实例?

python - 神经网络模型没有提高准确性。规模问题还是模型问题?

python - 如何在元素定界符上拆分列表

python - python 一次进行更多迭代