[英]I am trying to assign elements from one 2d array to another 2d array in python
So I have divided my issue into 2 parts, both parts should be able to fixed with the same solution.所以我将我的问题分为两部分,这两部分应该能够用相同的解决方案来解决。 Part 1 is the issue I have initially come across during testing of my code.
第 1 部分是我在测试代码时最初遇到的问题。 Where I am trying to assign elements from one 2d array to another but instead it only assigns the last elements to the array instead.
我试图将一个二维数组中的元素分配给另一个数组,但它只将最后一个元素分配给数组。 And part 2 is an issue that I will be facing later on but is still related.
第 2 部分是我稍后将面临但仍然相关的问题。
---PART 1--- - -第1部分 - -
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [[None]*4]*4
yval=0
for y in a:
xval = 0
for x in y:
b[yval][xval] = x
xval+=1
yval+=1
print("Grid A:")
print(a)
print("Grid B:")
print(b)
My Output我的输出
Grid A:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Grid B:
[[7, 8, 9, None], [7, 8, 9, None], [7, 8, 9, None], [7, 8, 9, None]]
My Goal我的目标
Grid A:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Grid B:
[[1, 2, 3, None], [4, 5, 6, None], [7, 8, 9, None], [None, None, None, None]]
I don't really understand what is causing each subarray in b to be assigned the same elements.我真的不明白是什么导致b 中的每个子数组都被分配了相同的元素。 including the last one even though the initial for loop only iterates 3 times.
即使最初的 for 循环只迭代 3 次,也包括最后一个。 Now there may be a simpler way to do this in python but I also need to be able to move one table over to another table but in a different location as well.
现在在 python 中可能有一种更简单的方法来做到这一点,但我还需要能够将一张桌子移到另一张桌子上,但也在不同的位置。
--- PART 2 --- - - 第2部分 - -
For example lets say I have a 2x2 array例如,假设我有一个 2x2 数组
[[a,b], [[a,b],
[c,d]] [光盘]]
And I want to place it in the bottom right corner of 4x4 array我想把它放在 4x4 数组的右下角
[[ , , , ], [[ , , , ],
[ , , , ], [ , , , ],
[ , , , ], [ , , , ],
[ , , , ]] [ , , , ]]
My code is我的代码是
a = [[1,2],[3,4]]
b = [[None]*4]*4
yval=0
for y in a:
xval = 0
for x in y:
b[yval+2][xval + 2] = x
xval+=1
yval+=1
print("Grid A:")
print(a)
print("Grid B:")
print(b)
My goal would be我的目标是
[[ , , , ], [[ , , , ],
[ , , , ], [ , , , ],
[ , ,a,b], [ , , a, b],
[ , ,c,d]] [, ,c,d]]
However my actual result is然而我的实际结果是
[[ , ,c,d], [[, ,c,d],
[ , ,c,d], [ , , c, d],
[ , ,c,d], [ , , c, d],
[ , ,c,d]] [, ,c,d]]
The problem comes form the definition of b which as defined is a list of 4 times the same sub-list as the following code shows问题来自 b 的定义,其中定义的列表是 4 次相同子列表的列表,如下面的代码所示
b = [[None]*4]*4
b[0][0] = 1
print(b)
outputs产出
[[1, None, None, None],
[1, None, None, None],
[1, None, None, None],
[1, None, None, None]]
b = [[None]*4 for _ in range(4)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.