Python 覆盖数组问题

在进行人工智能作业时,我试图通过将一个数组发送到生成函数中作为返回值来获取四个独立的数组。发送数组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提供矩阵的新副本。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注