In [161]: # %load 53
...: a = [[]] * 5
...: print(a)
...: for i in range(5):
...: a[i].append(9)
...: a[i] = a[i] * 5
...: print(a)
...:
[[], [], [], [], []]
[[9, 9, 9, 9, 9],
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]]
结果不应该是
[[9, 9, 9, 9, 9],
[9, 9, 9, 9, 9],
[9, 9, 9, 9, 9],
[9, 9, 9, 9, 9],
[9, 9, 9, 9, 9]]
这个吗?
搞清楚了
a = [[]] * 5产生的结果[[], [], [], [], []],其实是一个地址。
而a[i] = a[i] * 5的操作会重新分配地址
a = [[]] * 5
for i in range(5):
a[i].append(9)
print(a)