如何在python中的矩阵中编辑值?

时间:2020-02-03 21:12:37

标签: python

array = []
matrix = []

x = 0

while(x < 3):
    array.append(".")
    x += 1

x = 0

while(x < 3):
    matrix.append(array)
    x += 1

输出:

[['.', '.', '.'], ['.', '.', '.'], ['.', '.', '.']]

当我尝试将例如matrix [0] [1]更改为“ x”时,它将更改所有内部数组中的位置。有人可以解释为什么吗?

示例:

matrix[0][1] = "x"

输出:

[['.', 'x', '.'], ['.', 'x', '.'], ['.', 'x', '.']]

2 个答案:

答案 0 :(得分:4)

在第二个while循环中,您必须添加数组varibale的副本

public class MyLogoutSuccessHandler implements LogoutSuccessHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        if( authentication!=null ) {
            logger.debug("Signing out user: "+authentication.getName());
        } else {
            logger.debug("Unknown user reached logout success handler. (Perhaps he clicked 'sign out' twice.)");
        }

        // clear the cookie

        httpServletResponse.setStatus(HttpServletResponse.SC_OK);
        httpServletResponse.sendRedirect("/login?logout");
    }

}

否则,您将有3次相同的列表

while(x < 3):
    matrix.append(array.copy())
    x += 1

输出:

matrix[0][1] = 'x'
print(matrix)

答案 1 :(得分:-1)

在每个元素中出现['。','x','。']的原因是因为您的 array 是一个列表对象。这意味着只要您设置与该对象相等的值,您就会获得相同的内存位置。

另一种查看方式是,如果要设置array [2] ='o',那么矩阵将看起来像这样[['。','x','o'],['。,, 'x','o'],['。','x','o']]

我认为您正在寻找的解决方案虽然是深层副本,而不是浅层副本。您可以使用Python的内置list.copy()方法来实现此目的。

for x in range(0, 3):
    matrix.append(array.copy())
相关问题