gpt4 book ai didi

python - python 中的简单 n x n 矩阵不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 18:00:08 26 4
gpt4 key购买 nike

我用它来创建 'x' 的 4x4 矩阵:

listof=[] #table
nic=[] #row
max = 4 #tabele size
nic = ['x']*max #row of x-es
listof = [nic]*max #table of rows
print(listof) #it looks ok
listof[1][1] ="o" #changing one x to o
print(listof) # wrong since all rows have o on index 1

?怎么会?

顺便说一句:我知道如果我使用它就可以:

listof = [["x" for x in range(max)] for y in range(max)]

但是上面的代码有什么问题呢?谢谢

最佳答案

问题在于 listof 最终由对同一列表的四个引用组成。。因此,当您更改一行中的某个元素时,所有行中的元素都会发生更改。

关于python - python 中的简单 n x n 矩阵不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27826641/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com