首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何复制列表?

如何复制列表?
EN

Stack Overflow用户
提问于 2018-05-29 00:56:58
回答 2查看 0关注 0票数 0

在Python中克隆或复制列表有哪些选项?

使用new_list = my_lis,然后修改new_list当每次my_list改变。 为什么是这样?

EN

回答 2

Stack Overflow用户

发布于 2018-05-29 09:05:09

new_list = my_list,你实际上没有两个名单。分配正义的复制参考列表,而不是实际的列表,所以无论new_listmy_list分配后指向同一个列表。

要真正复制列表,你有各种可能性:

  • 可以切片: new_list = old_list[:]
  • 可以使用内置list()函数: new_list = list(old_list)
  • 可以使用泛型copy.copy()import copy new_list = copy.copy(old_list)
  • 如果列表包含对象并且你想要复制它们,请使用泛型copy.deepcopy()import copy new_list = copy.deepcopy(old_list)

例:

代码语言:javascript
复制
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))

结果:

代码语言:javascript
复制
original: ['foo', 5, 'baz']
slice: ['foo', 5]
list(): ['foo', 5]
copy: ['foo', 5]
deepcopy: ['foo', 1]
票数 0
EN

Stack Overflow用户

发布于 2018-05-29 10:07:15

我对各种方法进行速度比较:

  1. 10.59秒(105.9us / Itn) - copy.deepcopy(old_list)
  2. 10.16秒(101.6us / itn) - Copy()使用deepcopy复制类的纯python 方法
  3. 1.488秒(14.88us / itn) - 纯粹的python Copy()方法不复制类(只有字典/列表/元组)
  4. 0.325秒(3.25us / Itn) - for item in old_list: new_list.append(item)
  5. 0.217秒(2.17us / itn) - [i for i in old_list]列表理解
  6. 0.186秒(1.86us / itn) - copy.copy(old_list)
  7. 0.075秒(0.75us / Itn) - list(old_list)
  8. 0.053秒(0.53us /天) - new_list = []; new_list.extend(old_list)
  9. 0.039秒(0.39us / itn) - old_list[:]list slicing

所以最快的是列表切片。但要注意的是copy.copy()list[:]与python版本list(list)不同copy.deepcopy(),它不会复制列表中的任何列表,字典和类实例,因此如果原始文件发生更改,它们也会在复制列表中更改,反之亦然。

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100004569

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档