Python 是否仅替换一行中的值?
我有一个两行的列表,我只是试图替换一行中的一个变量,但它正在更改两行中的变量。代码如下:Python 是否仅替换一行中的值?,python,list,indexing,Python,List,Indexing,我有一个两行的列表,我只是试图替换一行中的一个变量,但它正在更改两行中的变量。代码如下: rowOfZeros_4cols = [] for i in range(0,4): rowOfZeros_4cols.append(0.) twoRows = [rowOfZeros_4cols, rowOfZeros_4cols] mat_Zeros = twoRows mat_Zeros[0][2] = 1. 输出如下所示: [[0.0, 0.0, 1.0, 0.0], [0.0,
rowOfZeros_4cols = []
for i in range(0,4):
rowOfZeros_4cols.append(0.)
twoRows = [rowOfZeros_4cols, rowOfZeros_4cols]
mat_Zeros = twoRows
mat_Zeros[0][2] = 1.
输出如下所示:
[[0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 1.0, 0.0]]
当我想要它看起来像:
[[0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]]
我做错了什么?这看起来应该是非常直截了当的
提前感谢,,
埃里克罪魁祸首是:
twoRows = [rowOfZeros_4cols, rowOfZeros_4cols]
对rowOfZeros\u 4cols
的两个引用不是两个单独的列表。是同一个对象,引用了两次
如果您更改它,看起来“两行”都已更改。相反,您总是更改同一行,只引用它两次
每次生成一个新的行:
twoRows = [[0] * 4, [0] * 4] # two independent lists of 4 zeros.
因为
twoorows
是一个包含两次相同列表的列表。可能的重复实际上更多的是重复的。