关于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(l