今天想要动态建一个列表, 很自然的想到
scores = [[]] * num
for i in range(nun):
scores[i].append(result)
结果得到的结果每个都一模一样, 才发现原来这样子出来的list里的list是共享内存的, 实验如下
a = [[]] * 8
print(a) # [[], [], [], [], [], [], [], []]
a[0].append(1) # 期望中a是[[1], [], [], [], [], [], [], []]
print(a) # 实际上a是[[1], [1], [1], [1], [1], [1], [1], [1]]
验证也很好验证
print(id(a[0])) # 140650110134408
print(id(a[1])) # 140650110134408 显然内存是共享的