简体   繁体   English

Python:在参数中包含矩阵的函数

[英]Python: Function with matrix in argument

So, in my program I have a "main" function, which changes two elements of a given matrix. 因此,在我的程序中,我有一个“主要”功能,该功能可以更改给定矩阵的两个元素。 The matrix is an element of a list (in the example the list is the variable solved ) and then I want to append three new elements. 矩阵是列表的一个元素(在示例中,列表是solved的变量),然后我想追加三个新元素。

def main(matrix,direction):
    index16 = indexOf(16,matrix)
    matrix[index16[0]][index16[1]],matrix[index16[0]-1][index16[1]]=matrix[index16[0]-1][index16[1]],matrix[index16[0]][index16[1]]

    return matrix

solved = [[[2,1,3,4],
      [5,6,7,8],
      [9,10,11,12],
      [13,14,15,16]
      ]]

not_solved = [[0,"up"],
          [0,"left"]
          ]

while not_solved:
    solved.append(main(solved[not_solved[0][0]],not_solved[0][1]))
break

When I execute the program, I can see the "solved" array. 当我执行程序时,我可以看到“已解决”数组。 However the initial matrix stays the same as in the beginning. 但是,初始矩阵与开始时相同。

[[[2, 1, 3, 4], [5, 6, 7, 8], [9, 10, 11, 16], [13, 14, 15, 12]], 
 [[2, 1, 3, 4], [5, 6, 7, 8], [9, 10, 11, 16], [13, 14, 15, 12]]]

How can I repair that? 我该如何修理?

Sorry for my English. 对不起我的英语不好。 I am still learning. 我仍在学习。

you need to copy your matrix inside main so the original matrix does not change 您需要在main内部复制矩阵,这样原始矩阵就不会改变

import copy

def main(matrix,direction):
    matrixcopy = copy.deepcopy(matrix)
    index16 = indexOf(16,matrixcopy)
    matrixcopy[index16[0]][index16[1]],matrixcopy[index16[0]-1][index16[1]]=matrixcopy[index16[0]-1][index16[1]],matrixcopy[index16[0]][index16[1]]
    return matrixcopy

Returns: 返回:

[[[2, 1, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 
 [[2, 1, 3, 4], [5, 6, 7, 8], [9, 10, 11, 16], [13, 14, 15, 12]]]

The problem is your main function 问题是你的主要功能

def main(matrix,direction):
    index16 = indexOf(16,matrix)
    matrix[index16[0]][index16[1]],matrix[index16[0]-1][index16[1]]=matrix[index16[0]-1][index16[1]],matrix[index16[0]][index16[1]]

    return matrix

In this function you're returning matrix, but you're also changing matrix, which is your original matrix. 在此函数中,您将返回矩阵,但您还将更改矩阵,这是您的原始矩阵。

Consider this simple example: 考虑以下简单示例:

>>> a=[1,2,3]
>>> def test(b):
    b[1]=4
    return b
>>> c = test(a)
>>> c
[1, 4, 3]
>>> a
[1, 4, 3]

A possible solution is to use the copy module 一个可能的解决方案是使用复制模块

>>> import copy
>>> a=[1,2,3]
>>> def test(b):
    c=copy.deepcopy(b)
    c[1]=4
    return c

>>> c = test(a)
>>> c
[1, 4, 3]
>>> a
[1, 2, 3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM