How to make a completely unshared copy of a complicated list? (Deep copy is not enough)

前端 未结 5 2046
无人及你
无人及你 2020-11-29 09:13

Have a look at this Python code:

a = [1, 2, 3]
b = [4, 5, 6]
c = [[a, b], [b, a]] # [[[1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]]
c[0][0].append(99)   # [         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 09:41

    To see Stephan's suggestion at work, compare the two outputs below:

    a = [1, 2, 3]
    b = [4, 5, 6]
    c = [[a, b], [b, a]]
    c[0][0].append(99)
    print c
    print "-------------------"
    a = [1, 2, 3]
    b = [4, 5, 6]
    c = [[a[:], b[:]], [b[:], a[:]]]
    c[0][0].append(99)
    print c
    

    The output is as follows:

    [[[1, 2, 3, 99], [4, 5, 6]], [[4, 5, 6], [1, 2, 3, 99]]]
    -------------------
    [[[1, 2, 3, 99], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]]
    

提交回复
热议问题