简体   繁体   中英

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. 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.

---PART 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. including the last one even though the initial for loop only iterates 3 times. 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.

--- PART 2 ---

For example lets say I have a 2x2 array
[[a,b],
[c,d]]

And I want to place it in the bottom right corner of 4x4 array
[[ , , , ],
[ , , , ],
[ , , , ],
[ , , , ]]

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],
[ , ,c,d]]

However my actual result is
[[ , ,c,d],
[ , ,c,d],
[ , ,c,d],
[ , ,c,d]]

Problem origin

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 = [[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]]

Solution

b = [[None]*4 for _ in range(4)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM