python - 为什么 l.insert(0, i) 在 python 中比 l.append(i) 慢?

标签 python algorithm list reverse

我测试了两种在 python 中反转列表的不同方法。

import timeit

value = [i for i in range(100)]
def rev1():
    v = []
    for i in value:
        v.append(i)
    v.reverse()

def rev2():
    v = []
    for i in value:
        v.insert(0, i)

print timeit.timeit(rev1)
print timeit.timeit(rev2)

有趣的是,将值插入第一个元素的第二种方法比第一种方法慢得多。

20.4851300716
73.5116429329

这是为什么?从操作上来说,在头部插入一个元素似乎并没有那么昂贵。

最佳答案

insert是一个 O(n)操作,因为它要求插入位置处或插入位置之后的所有元素向上移动一个。 append , 另一方面,通常是 O(1) (和 O(n) 在最坏的情况下,必须分配更多空间)。这解释了巨大的时差。

这些方法的时间复杂度已被详细记录 here .

我引用:

Internally, a list is represented as an array; the largest costs come from growing beyond the current allocation size (because everything must move), or from inserting or deleting somewhere near the beginning (because everything after that must move).

现在,回到您的代码,我们可以看到 rev1()是一个 O(n)实现而rev2()实际上是O(n<sup>2</sup>) , 所以 rev2() 是有道理的会慢很多。

关于python - 为什么 l.insert(0, i) 在 python 中比 l.append(i) 慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17635811/

相关文章:

python - 在python中读取csv文件时跳过第二行数据帧

c - 用 '%20' 替换字符串中的所有空格。假设字符串在字符串末尾有足够的空间来容纳额外的字符

寻找小于 x 的最大素数的算法

c# - 从列表中选择在成员函数上返回 true 的所有对象作为列表?

python - 从两个列表中的项目创建一个集合

java - Jython,只使用来自 Java 的 Python 的方法?

python - 从Python目录中读取所有图像并尝试将其存储在数组中

python - 返回列表中给定数字之前的数字

python - 如果在 "yield" block 内完成, "with"-ing 是否会触发 __exit__ 函数?

algorithm - 如何使用替换法解决以下递归问题?