7*4 2010-04-10 08:49 采纳率: 50%
浏览 325
已采纳

如何克隆或复制列表?

What are the options to clone or copy a list in Python?

Using new_list = my_list then modifies new_list every time my_list changes.
Why is this?

转载于:https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list

  • 写回答

18条回答 默认 最新

  • YaoRaoLov 2010-04-10 08:55
    关注

    With new_list = my_list, you don't actually have two lists. The assignment just copies the reference to the list, not the actual list, so both new_list and my_list refer to the same list after the assignment.

    To actually copy the list, you have various possibilities:

    • You can use the builtin list.copy() method (available since python 3.3):

      new_list = old_list.copy()
      
    • You can slice it:

      new_list = old_list[:]
      

      Alex Martelli's opinion (at least back in 2007) about this is, that it is a weird syntax and it does not make sense to use it ever. ;) (In his opinion, the next one is more readable).

    • You can use the built in list() function:

      new_list = list(old_list)
      
    • You can use generic copy.copy():

      import copy
      new_list = copy.copy(old_list)
      

      This is a little slower than list() because it has to find out the datatype of old_list first.

    • If the list contains objects and you want to copy them as well, use generic copy.deepcopy():

      import copy
      new_list = copy.deepcopy(old_list)
      

      Obviously the slowest and most memory-needing method, but sometimes unavoidable.

    Example:

    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))
    

    Result:

    original: ['foo', 5, 'baz']
    list.copy(): ['foo', 5]
    slice: ['foo', 5]
    list(): ['foo', 5]
    copy: ['foo', 5]
    deepcopy: ['foo', 1]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(17条)

报告相同问题?

悬赏问题

  • ¥15 从Freecad中宏下载的DesignSPHysics,出现如下问题是什么原因导致的(语言-python)
  • ¥30 notepad++ 自定义代码补全提示
  • ¥15 MATLAB有限差分法解一维边值问题
  • ¥200 内网渗透测试 横向渗透 Windows漏洞 Windows权限维持
  • ¥15 数据结构图的相关代码实现
  • ¥15 python中aiohttp.client_exceptions.ContentTypeError
  • ¥30 DeepLung肺结节检测生成最大froc值对应的epoch报错
  • ¥15 信号发生器如何将频率调大,步尽值改成10
  • ¥15 keil 5 编程智能家具,风扇台灯开关,人体感应等
  • ¥100 找一名渗透方面的专家