复制列表的最佳方法是什么?

68 投票
7 回答
82689 浏览
提问于 2025-04-11 09:31

复制一个列表的最佳方法是什么?我知道以下几种方法,哪种更好呢?或者还有其他方法吗?

lst = ['one', 2, 3]

lst1 = list(lst)

lst2 = lst[:]

import copy
lst3 = copy.copy(lst)

7 个回答

14

你还可以这样做:

a = [1, 2, 3]
b = list(a)
24

我经常使用:

lst2 = lst1 * 1

如果 lst1 里面包含其他容器(比如其他列表),你应该使用 Mark 提到的 copy 库里的 deepcopy。


更新:解释 deepcopy

>>> a = range(5)
>>> b = a*1
>>> a,b
([0, 1, 2, 3, 4], [0, 1, 2, 3, 4])
>>> a[2] = 55 
>>> a,b
([0, 1, 55, 3, 4], [0, 1, 2, 3, 4])

你可能会看到只有一个改变……

我现在试试用一个列表的列表

>>> 
>>> a = [range(i,i+3) for i in range(3)]
>>> a
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
>>> b = a*1
>>> a,b
([[0, 1, 2], [1, 2, 3], [2, 3, 4]], [[0, 1, 2], [1, 2, 3], [2, 3, 4]])

这样不太好读,让我用 for 循环打印一下:

>>> for i in (a,b): print i   
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
>>> a[1].append('appended')
>>> for i in (a,b): print i

[[0, 1, 2], [1, 2, 3, 'appended'], [2, 3, 4]]
[[0, 1, 2], [1, 2, 3, 'appended'], [2, 3, 4]]

你看到了吗?它也加到了 b[1] 里,所以 b[1] 和 a[1] 是同一个对象。

现在试试用 deepcopy

>>> from copy import deepcopy
>>> b = deepcopy(a)
>>> a[0].append('again...')
>>> for i in (a,b): print i

[[0, 1, 2, 'again...'], [1, 2, 3, 'appended'], [2, 3, 4]]
[[0, 1, 2], [1, 2, 3, 'appended'], [2, 3, 4]]
111

如果你想要一个浅拷贝(也就是说,里面的元素不会被复制),可以使用:

lst2=lst1[:]

如果你想要做一个深拷贝,那就可以使用复制模块:

import copy
lst2=copy.deepcopy(lst1)

撰写回答