填充整列的二维列表

2D list filling a whole column

我想要一个生成邻接矩阵的算法。输入是一个一维列表,它输出一个二维列表,其中包含数字的变化方式。这是我的:

n_clusters = 5
user = [4, 4, 4, 2, 3, 3, 0, 0, 0]  # input array

movement_counts = [[0] * n_clusters] * n_clusters  # row is from, col is to

prev_label = user[0]
for label in user[1:]:
    if label != prev_label:
        movement_counts[prev_label][label] += 1
    prev_label = label

这个returns

[[1, 0, 1, 1, 0], 
 [1, 0, 1, 1, 0],
 [1, 0, 1, 1, 0],
 [1, 0, 1, 1, 0],
 [1, 0, 1, 1, 0]]

但我想要它 return 这个:

[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 1, 0],
 [1, 0, 0, 0, 0],
 [0, 0, 1, 0, 0]]

为什么它用数字而不是一个元素填充整列?

替换:

movement_counts = [[0] * n_clusters] * n_clusters

与:

movement_counts = [[0] * n_clusters for _ in range(n_clusters)]

因为,movement_counts = [[0] * n_clusters] * n_clusters生成的列表包含指向内存中相同引用的子列表,因此如果您更改任何子列表中的任何元素,所有子列表都会发生更改。