复制列表的最佳方法是什么?
问题描述:
复制列表的最佳方法是什么?我知道以下几种方式,哪一种更好?或者有其他方法吗?
What is the best way to copy a list? I know the following ways, which one is better? Or is there another way?
lst = ['one', 2, 3]
lst1 = list(lst)
lst2 = lst[:]
import copy
lst3 = copy.copy(lst)
答
如果你想要一个浅拷贝(元素不被拷贝)使用:
If you want a shallow copy (elements aren't copied) use:
lst2=lst1[:]
如果要进行深拷贝,请使用复制模块:
If you want to make a deep copy then use the copy module:
import copy
lst2=copy.deepcopy(lst1)