Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中简单表的奇怪行为_Python_Matrix - Fatal编程技术网

Python中简单表的奇怪行为

Python中简单表的奇怪行为,python,matrix,Python,Matrix,我是Python的初学者。的动态编程解决方案需要一个初始化表,该表基本上可以如下所示: [ [1,0,0,0], [1,0,0,0], [1,0,0,0] ] 哪一个表我是这样指定的: table=[[1]+[0]*3]*3 现在,如果我写 table[1][2]=1 for x in table: print x 我得到了一份: [1, 0, 2, 0] [1, 0, 2, 0] [1, 0, 2, 0] 我也不知道为什么整列都会被更改,而不是指定的数字。错误在您没有显示的代码中。你大

我是Python的初学者。的动态编程解决方案需要一个初始化表,该表基本上可以如下所示:

[
[1,0,0,0],
[1,0,0,0],
[1,0,0,0]
]
哪一个表我是这样指定的:

table=[[1]+[0]*3]*3
现在,如果我写

table[1][2]=1
for x in table: print x
我得到了一份:

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

我也不知道为什么整列都会被更改,而不是指定的数字。

错误在您没有显示的代码中。你大概是这样草签你的名单的

a = [1, 0, 0, 0]
table = [a, a, a]

或者类似的东西,这会导致一个列表包含三倍于同一列表对象的内容。如果修改此单个对象,它将在引用它的任何位置更改,因为它只是单个对象

如果需要更多详细信息,请向我们展示创建表的代码

初始化
表的正确方法是

table = [[1, 0, 0, 0] for i in range(3)]
或者干脆

table = [[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]
这项工作:

t = [
    [1,0,0,0],
    [1,0,0,0],
    [1,0,0,0],
]

t[1][2]=1
for x in t: print x

@安德拉斯科瓦茨:欢迎来到SO。我的帖子已经回答了你的新问题。
t = [
    [1,0,0,0],
    [1,0,0,0],
    [1,0,0,0],
]

t[1][2]=1
for x in t: print x