5 回答

TA貢獻(xiàn)1845條經(jīng)驗(yàn) 獲得超8個(gè)贊
菲利克斯已經(jīng)提供了一個(gè)很好的答案,但我想我會(huì)對(duì)各種方法進(jìn)行速度比較:
10.59秒(105.9us / itn) -
copy.deepcopy(old_list)
10.16秒(101.6us / itn) -
Copy()
使用deepcopy復(fù)制類的純python 方法1.488秒(14.88us / itn) - 純python
Copy()
方法不復(fù)制類(只有dicts / lists / tuples)0.325秒(3.25us / itn) -
for item in old_list: new_list.append(item)
0.217秒(2.17us / itn) -
[i for i in old_list]
(列表理解)0.186秒(1.86us / itn) -
copy.copy(old_list)
0.075秒(0.75us / itn) -
list(old_list)
0.053秒(0.53us / itn) -
new_list = []; new_list.extend(old_list)
0.039秒(0.39us / itn) -
old_list[:]
(列表切片)
所以最快的是列表切片。但請(qǐng)注意copy.copy()
,list[:]
并且list(list)
,與copy.deepcopy()
python版本不同,它不會(huì)復(fù)制列表中的任何列表,字典和類實(shí)例,因此如果原件發(fā)生更改,它們也會(huì)在復(fù)制的列表中更改,反之亦然。
(這是腳本,如果有人有興趣或想提出任何問題:)
from copy import deepcopy
class old_class:
def __init__(self):
self.blah = 'blah'
class new_class(object):
def __init__(self):
self.blah = 'blah'
dignore = {str: None, unicode: None, int: None, type(None): None}
def Copy(obj, use_deepcopy=True):
t = type(obj)
if t in (list, tuple):
if t == tuple:
# Convert to a list if a tuple to
# allow assigning to when copying
is_tuple = True
obj = list(obj)
else:
# Otherwise just do a quick slice copy
obj = obj[:]
is_tuple = False
# Copy each item recursively
for x in xrange(len(obj)):
if type(obj[x]) in dignore:
continue
obj[x] = Copy(obj[x], use_deepcopy)
if is_tuple:
# Convert back into a tuple again
obj = tuple(obj)
elif t == dict:
# Use the fast shallow dict copy() method and copy any
# values which aren't immutable (like lists, dicts etc)
obj = obj.copy()
for k in obj:
if type(obj[k]) in dignore:
continue
obj[k] = Copy(obj[k], use_deepcopy)
elif t in dignore:
# Numeric or string/unicode?
# It's immutable, so ignore it!
pass
elif use_deepcopy:
obj = deepcopy(obj)
return obj
if __name__ == '__main__':
import copy
from time import time
num_times = 100000
L = [None, 'blah', 1, 543.4532,
['foo'], ('bar',), {'blah': 'blah'},
old_class(), new_class()]
t = time()
for i in xrange(num_times):
Copy(L)
print 'Custom Copy:', time()-t
t = time()
for i in xrange(num_times):
Copy(L, use_deepcopy=False)
print 'Custom Copy Only Copying Lists/Tuples/Dicts (no classes):', time()-t
t = time()
for i in xrange(num_times):
copy.copy(L)
print 'copy.copy:', time()-t
t = time()
for i in xrange(num_times):
copy.deepcopy(L)
print 'copy.deepcopy:', time()-t
t = time()
for i in xrange(num_times):
L[:]
print 'list slicing [:]:', time()-t
t = time()
for i in xrange(num_times):
list(L)
print 'list(L):', time()-t
t = time()
for i in xrange(num_times):
[i for i in L]
print 'list expression(L):', time()-t
t = time()
for i in xrange(num_times):
a = []
a.extend(L)
print 'list extend:', time()-t
t = time()
for i in xrange(num_times):
a = []
for y in L:
a.append(y)
print 'list append:', time()-t
t = time()
for i in xrange(num_times):
a = []
a.extend(i for i in L)
print 'generator expression extend:', time()-t

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊

TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊
已經(jīng)有許多答案告訴你如何制作一個(gè)正確的副本,但沒有一個(gè)人說你為什么原來的'副本'失敗了。
Python不會(huì)將值存儲(chǔ)在變量中; 它將名稱綁定到對(duì)象。您的原始作業(yè)采用了所引用的對(duì)象并將其my_list
綁定new_list
。無論您使用哪個(gè)名稱,仍然只有一個(gè)列表,因此在引用它時(shí)所做的更改將在引用my_list
時(shí)保持不變new_list
。此問題的其他每個(gè)答案都為您提供了創(chuàng)建要綁定的新對(duì)象的不同方法new_list
。
列表的每個(gè)元素都像一個(gè)名稱,因?yàn)槊總€(gè)元素都非唯一地綁定到一個(gè)對(duì)象。淺拷貝創(chuàng)建一個(gè)新列表,其元素綁定到與以前相同的對(duì)象。
new_list = list(my_list) # or my_list[:], but I prefer this syntax# is simply a shorter way of:new_list = [element for element in my_list]
要使列表副本更進(jìn)一步,請(qǐng)復(fù)制列表引用的每個(gè)對(duì)象,并將這些元素副本綁定到新列表。
import copy # each element must have __copy__ defined for this...new_list = [copy.copy(element) for element in my_list]
這還不是一個(gè)深層副本,因?yàn)榱斜淼拿總€(gè)元素都可以引用其他對(duì)象,就像列表綁定到它的元素一樣。以遞歸方式復(fù)制列表中的每個(gè)元素,然后復(fù)制每個(gè)元素引用的每個(gè)其他對(duì)象,依此類推:執(zhí)行深層復(fù)制。
import copy# each element must have __deepcopy__ defined for this...new_list = copy.deepcopy(my_list)
有關(guān)復(fù)制中的邊角情況的更多信息,請(qǐng)參閱文檔。

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超5個(gè)贊
使用 thing[:]
>>> a = [1,2]
>>> b = a[:]
>>> a += [3]
>>> a
[1, 2, 3]
>>> b
[1, 2]
>>>
添加回答
舉報(bào)