在进行人工智能作业时,我试图通过将一个数组发送到生成函数中作为返回值来获取四个独立的数组。发送数组1时一切正常。但是当发送数组2、3和4时,它会覆盖之前生成的数组。目前最后一个数组array4的输出是:
['#', '#', '#', '#', '#']['#', 'G', '☐', 'G', '#']['#', '☐', 'P', '•', '#']['#', 'P', '•', 'P', '#']['#', '#', '#', '#', '#']
array4的理想输出是:
['#', '#', '#', '#', '#']['#', 'G', '•', 'G', '#']['#', '☐', '☐', '•', '#']['#', 'P', '•', '•', '#']['#', '#', '#', '#', '#']
以下是我的完整Python代码:
def solver():matrix = [['#', '#', '#', '#', '#'], ['#', 'G', '•', 'G', '#'], ['#', '☐', '☐', '•', '#', ], ['#', '•', 'P', '•', '#'], ['#', '#', '#', '#', '#']]countx = 0county = 0cordp = []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 positiecordp[0], cordp[1] = cordp[1]-1, cordp[0]-1n = 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 matrixnewsolver()
回答:
正如评论中@人名指出的,由于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
提供矩阵的新副本。