python 浅拷贝和深拷贝 关于在循环中使用list.append(),插入数据被覆盖的问题

 

关于Python中,循环后使用list.append(),数据被覆盖的问题

例子:

def make_list_of_lists(n):
    the_list = []
    sublist = []
    while n > 0:
        the_list.append(sublist)
        sublist.append(len(sublist) + 1)
        n = n - 1
    return the_list

测试用例:

print(make_list_of_lists(0))
print(make_list_of_lists(1)) 
print(make_list_of_lists(5))

期望输出结果:

[]

[[]]

[[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]

实际输出结果:
[]
[[1]]
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]

解决方案:

1.浅拷贝

def make_list_of_lists(n):
    the_list = []
    sublist = []
    while n > 0:
        ptable= sublist[:]
        the_list.append(ptable)
        sublist.append(len(sublist) + 1)
        n = n - 1
    return the_list

2.深拷贝

import copy
def make_list_of_lists(n):
    the_list = []
    sublist = []
    while n >0:
        the_list.append(copy.deepcopy(sublist))
        sublist.append(len(sublist) + 1)
        n = n - 1
    return the_list

 


版权声明:本文为qq_41109945原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。