'the same object is filling every colon in a matrix
I have a matrix that will be filled with objects of the same class, I have done this using 2 for loops.
def main(W,H):
field=[[None]*W]*H
for i in range(H):
for j in range(W):
field[i][j]=tile()
# Are the same
print(id(field[0][1]))
print(id(field[1][1]))
print(id(field[2][1]))
print(id(field[3][1]))
# Are diffret
print(id(field[0][0]))
print(id(field[0][1]))
print(id(field[0][2]))
print(id(field[0][3]))
I need all the objects to be different so I can edit and use them separately.
Solution 1:[1]
Try
def main(W,H):
field=[]
for i in range(0, H):
row=[]
for j in range(0, W):
row+=[None]
field+=[list(row.copy())].copy()
field[0][1]="Test different value" #debug
"""
for i in range(H):
for j in range(W):
field[i][j]=tile()
"""
for i in range (0, H): #debug
for j in range (0, W):
print(field[i][j], i, j)
main(3,3)
All items do have the same id, however, changing the value of one of them doesn't affect the others.
I have changed the way field is generated. Probably lists were linked as you didn't used list.copy()
Output:
None 0 0
Test different value 0 1
None 0 2
None 1 0
None 1 1
None 1 2
None 2 0
None 2 1
None 2 2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vale |
