Python中如何复制一个列表【面试题详解】

今天爱分享给大家带来Python中如何复制一个列表【面试题详解】,希望能够帮助到大家。
可以用切片的方法


new_list = old_list[:]

可以使用list()函数


new_list = list(old_list)

可以使用copy.copy(),比list()稍慢,因为它首先去查询old_list的数据类型


import copy
new_list = copy.copy(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[:]
c = list(a)
d = copy.copy(a)
e = copy.deepcopy(a)

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

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

结果:


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

效率简单比较


10.59 - copy.deepcopy(old_list)
10.16 - pure python Copy() method copying classes with deepcopy
1.488 - pure python Copy() method not copying classes (only dicts/lists/tuples)
0.325 - for item in old_list: new_list.append(item)
0.217 - [i for i in old_list] (a list comprehension)
0.186 - copy.copy(old_list)
0.075 - list(old_list)
0.053 - new_list = []; new_list.extend(old_list)
0.039 - old_list[:] (list slicing)

人已赞赏
Python

Python中如何获取一个列表的长度【面试题详解】

2020-12-27 16:30:54

Python

Python中列表的append和extend的区别【面试题详解】

2020-12-27 16:34:39

'); })();