Python 二维查询..
我在 python 中看到了一个非常不寻常的行为。请让我知道我做错了什么!
bc = [[0]*(n+1)]*(n+1)
for i in range(n+1):
bc[i][i] = 1
print (bc)
输出
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
我试图将二维数组的对角线元素初始化为 1,但它用 1 初始化所有元素。我认为我在访问二维数组时做错了。
另外,请让我知道如何使用两个循环来访问二维数组的所有元素..我的下一步..
谢谢。
I am seeing a very unusual behavior in python.. Kindly let me know what am i doing wrong!!
bc = [[0]*(n+1)]*(n+1)
for i in range(n+1):
bc[i][i] = 1
print (bc)
Output
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
I am trying to initialize the diagonal elements of two dimensional array to 1, but it is initializing all the elements with 1. I think I am doing something wrong with accessing two dimensional Array..
Also, kindly let me know how can I use two loops to access all the elements of two dimensional array.. my next step..
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的数组初始化不正确。初始化二维数组的正确方法是这样的:
这是一个常见的错误,但是 * 运算符将指针复制到列表而不是复制列表,因此虽然看起来有一个二维列表,但实际上有一个一维列表指向同一个列表的指针。
Your array is initialized incorrectly. The correct way to initialize a 2d array is this:
It's a common mistake, but the * operator copies the pointer to an list rather than copying the list, so while it looks like you have a 2d list, you actually have a 1d list of pointers to the same list.
问题是数组中的每个数组都是内存中的同一个数组。你每次都需要一个新的数组。例如,[[0]]*6 将在一个数组中创建 6 个相同的数组,编辑其中一个将更新其他数组。
例如
,这里通过简单地将 bc 编辑为 n+1 个不同的数组来修复:
the problem is that each array in your array is the same array in memory. you need a new array each time. the [[0]]*6 will for example make 6 of the same arrays in an array, editing one of them will update the other ones.
e.g.
here is a fix by simply editing bc to be n+1 different arrays:
试试这个:
在您的示例中,您只有一个 (!)
[0]
实例,该实例被多次引用。因此,如果您更改该实例,所有引用都会更改。Try this one:
In your example you have only one (!) instance of
[0]
which is referenced multiple times. So if you change that instance, all references are changed.