Python implements the assignment of one-dimensional sequence loops to two-dimensional sequence problems, asking for help.

python implements the assignment of one-dimensional sequence loops to two-dimensional sequence problems, resorting to

a = [0 br 0]

b = []

for i in range (4):

a[3] = i
b.append(a)

print b

what you want to achieve is
[[0,0,0,0], [0,0,0,1], [0,0,0,2], [0,0,0,3]]

but the reality is:
[[0,0,0,3], [0,0,0,3], [0,0,0,3], [0,0,0,3]]

where is the problem?

Sep.24,2021

in python, copies of list are mostly pointer copies, or references.

that is, every time you execute b.append (a) , b ends with a (instead of a copy of a); by the end of the loop, all four elements of b are a, and the value of an is [0,0,0,3] , so all you see in b is [0,0,0,3] .

the solution is to create a new list for b. There are many specific ways to do this, so I'll leave it to you to think about

.
Menu