def print():
info = [0,0]
map = [[info for col in range(n 1)] for row in range(n 1)]
map[1][1][0] = 1 # i hope this ==> map[1][1] = [1,0]
but result this enter image description here
CodePudding user response:
You need to copy the array info
:
map = [[info.copy() for col in range(n 1)] for row in range(n 1)]
So that it doesn't refer to the same object.
Note: Don't name variables as keyword names, such as map
.
Instead something like:
variable = [[info.copy() for col in range(n 1)] for row in range(n 1)]
CodePudding user response:
info
represents the same list for each result in the comprehension. When this list is modified later, it appears to affect all the results because it is the same shared object that is modified.
One way is to avoid the issue is to create a new list explicitly using a literal:
map = [[[0, 1] for col in range(n 1)] for row in range(n 1)]
Or, as Keith pointed out, create a copy of the original list:
map = [[info[:] for col in range(n 1)] for row in range(n 1)]
Also, don’t use the same-name as built-ins — ie. rename map
to something else.