When I tried to replace a part of a 2D array in python, I made a mistake in the creation method and got stuck. As a little memorandum. ..
It's very easy, but if you had a 2D array consisting of 5 * 4 0s, you wanted to replace some of them with 1.
#before:A two-dimensional array like this
[[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0],
[0,0,0,0,0]]
'''''''''''''
|
|
|
\|/
'''''''''''''
#after:I wanted to replace it like this
[[0,0,0,0,0],
[0,0,1,0,0],
[0,0,0,0,0],
[0,0,0,0,0]]
First of all, from the mistake I made,
#Wrong example
#Create an initialized array
map_list = [[0]*W]*H
#map_Replace by specifying index of list
map_list[1][2] = 1
#Try to display the result
for line in map_list:
print(line)
result:
[0, 0, 1, 0, 0]
[0, 0, 1, 0, 0]
[0, 0, 1, 0, 0]
[0, 0, 1, 0, 0]
Why! ?? You have specified the position properly! ?? ** For some reason executed for all columns **
In python you can check the id by the following method
print(id(a))
If you check the two-dimensional array earlier,
[1650962624, 1650962624, 1650962656, 1650962624, 1650962624]
[1650962624, 1650962624, 1650962656, 1650962624, 1650962624]
[1650962624, 1650962624, 1650962656, 1650962624, 1650962624]
[1650962624, 1650962624, 1650962656, 1650962624, 1650962624]
Apparently the cause is that the id of the column is covered.
Now, the problem was the array creation part.
map_list = [[0]*5]*4
Create using list comprehension as follows
map_list = [[0 for i in range(5)] for r in range(4)]
Let's actually replace
#Create an initialized array
map_list = [[0 for i in range(5)] for r in range(4)]
#map_Replace by specifying index of list
map_list[1][2] = 1
#Try to display the result
for line in map_list:
print(line)
output:
[0, 0, 0, 0, 0]
[0, 0, 1, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
So, I was told that you have to be careful when initializing a two-dimensional array. There is a pitfall in an unexpected place.
Recommended Posts