[英]Python overwriting array when returned from function
對於人工智能評估,我試圖通過將一個數組作為返回值發送到generate函數中來獲得4個單獨的數組。 發送陣列1時,它可以正常工作。 但是,當發送數組2、3和4時,它將覆蓋先前生成的數組。 此時最后一個數組array4的輸出為:
['#', '#', '#', '#', '#']
['#', 'G', '☐', 'G', '#']
['#', '☐', 'P', '•', '#']
['#', 'P', '•', 'P', '#']
['#', '#', '#', '#', '#']
array4的理想輸出是:
['#', '#', '#', '#', '#']
['#', 'G', '•', 'G', '#']
['#', '☐', '☐', '•', '#']
['#', 'P', '•', '•', '#']
['#', '#', '#', '#', '#']
下面是我的完整Python代碼:
def solver():
matrix = [['#', '#', '#', '#', '#'], ['#', 'G', '•', 'G', '#'], ['#', '☐', '☐', '•', '#', ],
['#', '•', 'P', '•', '#'], ['#', '#', '#', '#', '#']]
countx = 0
county = 0
cordp = []
for x in matrix:
county += 1
for y in x:
countx += 1
if y == 'P':
cordp = [countx, county]
countx = 0
print(x)
# nieuwe stap
# wat is huidige positie
cordp[0], cordp[1] = cordp[1]-1, cordp[0]-1
n = gen_matrix(matrix, cordp, 0,-1)
e = gen_matrix(matrix, cordp, 1,0)
s = gen_matrix(matrix, cordp, 0,1)
w = gen_matrix(matrix, cordp, -1,0)
for x in n:
print(x)
def gen_matrix(matrixnew, cordp, x, y):
print (x)
print(y)
if matrixnew[cordp[0]+y][cordp[1]+x] == '☐':
if matrixnew[cordp[0]+y*2][cordp[1]+x*2] == '#':
print("ik kan doos niet verplaatsen")
else:
print("IK HEB EEN BOX en kan deze verplaatsen")
matrixnew[cordp[0]+y*2][cordp[1]+x*2] = '☐'
matrixnew[cordp[0]+y][cordp[1]+x] = 'P'
matrixnew[cordp[0]][cordp[1]] = '•'
elif matrixnew[cordp[0]+y][cordp[1]+x] == '•':
print("ik heb een bolletje")
matrixnew[cordp[0]+y][cordp[1]+x] = 'P'
matrixnew[cordp[0]][cordp[1]] = '•'
elif matrixnew[cordp[0]+y][cordp[1]+x] == '#':
print("ik heb een muur")
return matrixnew
solver()
正如Paul在評論中指出的那樣,由於python通過引用而不是通過值傳遞列表,因此您正在覆蓋矩陣。
解決方法是在修改矩陣之前先復制它們。
我們可以復制一個二維矩陣,即列表列表,如下所示:
matrix_copy = [list(row) for row in original_matrix]
所以我們可以取代這個
n = gen_matrix(matrix, cordp, 0,-1)
e = gen_matrix(matrix, cordp, 1,0)
s = gen_matrix(matrix, cordp, 0,1)
w = gen_matrix(matrix, cordp, -1,0)
有了這個
n = gen_matrix([list(row) for row in matrix], cordp, 0,-1)
e = gen_matrix([list(row) for row in matrix], cordp, 1,0)
s = gen_matrix([list(row) for row in matrix], cordp, 0,1)
w = gen_matrix([list(row) for row in matrix], cordp, -1,0)
為每次運行給gen_matrix
一個新的矩陣副本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.