在Python中复制一个列表list


在Python中如何复制一个列表

常见的错误是:mylist2 = mylist1,这实际上是同一个列表,指针地址是相同的。

复制列表的方法

你可以使用builtin list.copy()方法(从python 3.3开始提供):

new_list = old_list.copy()

你可以使用切片:

new_list = old_list[:]

您可以使用内置list()功能:

new_list = list(old_list)

你可以使用泛型copy.copy():

import copy
new_list = copy.copy(old_list)

这有点慢,list()因为它必须首先找出数据类型old_list。

如果列表包含对象,并且您也想要复制它们,请使用泛型copy.deepcopy():

import copy
#深度拷贝,递归拷贝对象
new_list = copy.deepcopy(old_list)

实例

import copy

class Foo(object):
    def __init__(self, val):
         self.val = val

    def __repr__(self):
        return str(self.val)

foo = Foo(1)

a = ['foo', foo]
b = a.copy()
c = a[:]
d = list(a)
e = copy.copy(a)
f = copy.deepcopy(a)

# edit orignal list and instance
a.append('baz')
foo.val = 5

print('original: %r\n list.copy(): %r\n slice: %r\n list(): %r\n copy: %r\n deepcopy: %r'
      % (a, b, c, d, e, f))

结果:

original: ['foo', 5, 'baz']
list.copy(): ['foo', 5]
slice: ['foo', 5]
list(): ['foo', 5]
copy: ['foo', 5]
deepcopy: ['foo', 1]

效率

10.59 sec (105.9us/itn) -  copy.deepcopy(old_list)
10.16 sec (101.6us/itn) -  python Copy() 方法使用deepcopy拷贝类
1.488 sec (14.88us/itn) -  python Copy() 没有深度拷贝 (只有 dicts/lists/tuples)
0.325 sec (3.25us/itn) - for item in old_list: new_list.append(item)
0.217 sec (2.17us/itn) - [i for i in old_list] (a list comprehension)
0.186 sec (1.86us/itn) - copy.copy(old_list)
0.075 sec (0.75us/itn) - list(old_list)
0.053 sec (0.53us/itn) - new_list = []; new_list.extend(old_list)
0.039 sec (0.39us/itn) - old_list[:] (list slicing)