从函数返回时Python覆盖数组

时间:2017-10-07 14:49:55

标签: python arrays artificial-intelligence overwrite

对于人工智能分配,我试图通过将数组作为返回值发送到生成函数来获得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()

1 个答案:

答案 0 :(得分:0)

正如保罗在评论中指出的那样,你要覆盖你的矩阵,因为python通过引用而不是按值传递列表。

修复是在修改矩阵之前复制矩阵。

我们可以复制一个2d矩阵,即列表列表,如下所示:

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矩阵的新副本。