import numpy as np
table = [[0]*5]*5
table[0][0] = -1
print(table[0][0])
print(np.reshape(table, (5, 5)))
table2 = [[0,0,0,0,0]*5]
table2[0][0] = -1
print(table2[0][0])
print(np.reshape(table2, (5, 5)))
#table
-1
[[-1 0 0 0 0]
[-1 0 0 0 0]
[-1 0 0 0 0]
[-1 0 0 0 0]
[-1 0 0 0 0]]
#table2
-1
[[-1 0 0 0 0]
[ 0 0 0 0 0]
[ 0 0 0 0 0]
[ 0 0 0 0 0]
[ 0 0 0 0 0]]
What's the reason for the results?
python
table = [[0]*5]*5
table[0][0] = -1
print(table)
print(table[0][0])
print(id(table[0]), id(table[2]), id(table[3]))
######################
# [[-1, 0, 0, 0, 0], [-1, 0, 0, 0, 0], [-1, 0, 0, 0, 0], [-1, 0, 0, 0, 0], [-1, 0, 0, 0, 0]]
# -1
# 2106814512832 2106814512832 2106814512832
The last result shows that table[0]
table[1]
table[2]
is not a different list, but the same list (not just the same value).
It's a bit confusing when I first did Python. You should also be careful about transferring list factors as a function.
828 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
558 Who developed the "avformat-59.dll" that comes with FFmpeg?
561 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
583 GDB gets version error when attempting to debug with the Presense SDK (IDE)
© 2024 OneMinuteCode. All rights reserved.