在 python 中复制列表时使用 list() 的复杂性是什么?

What is the complexity of using list() while copying a list in python?

我有一个列表:

a = [1,2,3,4]

现在我想将列表 a 复制为列表 b

b = list(a)

我想知道复制列表的步骤的复杂性a

当您对可变数据类型执行复制操作时:

b = list(a)
a is b # False

它将整个数据复制到另一个内存位置,时间复杂度由列表的总大小定义,即 O(n)

如果你像下面这样分配它(Aliasing):

b = a
a is b # True

那么时间复杂度就是O(1)

详情请看here

复制列表时:

  • list.copy()
  • list[:]
  • list()

它遍历所有元素。所以时间复杂度由列表的大小定义,即 O(n)

浅拷贝,切片需要O(n) 因为 Python 遍历列表中的所有元素并将对象引用的副本添加到新列表(按引用复制)。

浅拷贝

list.copy()

列表切片

list[:]

使用built-in列表构造函数list(...)

list()

使用列表理解

[e for e in lst]