Copying nested lists in Python

后端 未结 2 1762
悲&欢浪女
悲&欢浪女 2020-11-22 13:32

I want to copy a 2D list, so that if I modify one list, the other is not modified.

For a one-dimensional list, I just do this:

a = [1, 2]
b = a[:]
         


        
2条回答
  •  执笔经年
    2020-11-22 13:46

    For a more general solution that works regardless of the number of dimensions, use copy.deepcopy():

    import copy
    b = copy.deepcopy(a)
    

提交回复
热议问题