使用"[[0] * x] * y"在Python中初始化矩阵.创建链接的行? [英] Initializing matrix in Python using "[[0]*x]*y" creates linked rows?

查看:156
本文介绍了使用"[[0] * x] * y"在Python中初始化矩阵.创建链接的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如此初始化矩阵似乎会链接各行,以便当一行发生更改时,它们都将发生变化:

Initializing a matrix as so seems to link the rows so that when one row changes, they all change:

>>> grid = [[0]*5]*5
>>> grid
[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]
>>> grid[2][2] = 1
>>> grid
[[0, 0, 1, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 1, 0, 0]]

如何避免这种情况?

推荐答案

grid = [[0]*5 for i in range(5)]

注意:[int] * 5复制int 5次(但是复制int时,您只需复制值). [列表] * 5将引用复制到同一列表5次. (当您复制列表时,您将复制指向内存中该列表的引用).

Note: [int]*5 copies the int 5 times (but when you copy an int you just copy the value). [list]*5 copies the reference to the same list 5 times. (when you copy a list you copy the reference that points to the list in memory).

这篇关于使用"[[0] * x] * y"在Python中初始化矩阵.创建链接的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆