我只想在2D数组的第一个索引中追加1,但为什么数组的所有元素都会追加1?
num_count = [[]]*5
num_count[0].append(1)
print(num_count)
output : [[1], [1], [1], [1], [1]]
我预期的答案是[[1],[],[],[],[]]
当您定义像num_count = [[]]*5
这样的列表时,它会将相同的列表放在容器列表的所有五个位置
num_count = [[]]*5
for sub in num_count:
print(id(sub))
输出为
id of sublist is 140592936606336
id of sublist is 140592936606336
id of sublist is 140592936606336
id of sublist is 140592936606336
id of sublist is 140592936606336
他们都在同一个名单上。
所以为了避免这种问题,你可以使用列表理解。
num_count = [[] for _ in range(5)]
现在,如果在0个位置添加一个元素,它将只附加在0位置。
num_count = [[] for _ in range(5)]
num_count[0].append(1)
print(num_count)
输出为
[[1], [], [], [], []]