java - 来自 python 的转置矩阵

标签 java python python-3.x algorithm

<分区>

我真的不明白这里的逻辑.......

def transpose(A):
    output = [['']*len(A)] * len(A[0])
    for j in range(len(A[0])):
        for i in range(len(A)):
            output[j][i] = A[i][j]
    return output

输入:[[1,2,3],[4,5,6],[7,8,9]]

预期输出:[[1,4,7],[2,5,8],[3,6,9]]

我的输出:[[3,6,9], [3,6,9], [3,6,9]]

我知道我可以使用 zip 轻松解决这个问题,但我只想知道为什么这段代码会返回重复的列表。

新的更新,我添加了一些打印以了解过程

def transpose(A):
    output = [['']*len(A)] * len(A[0])
    for j in range(len(A[0])):
        for i in range(len(A)):
            output[j][i] = A[i][j]
            print(j)
            print(i)
            print(output)
    return output

输出是:

0
0
[[1, '', ''], [1, '', ''], [1, '', '']]
0
1
[[1, 4, ''], [1, 4, ''], [1, 4, '']]
0
2
[[1, 4, 7], [1, 4, 7], [1, 4, 7]]
1
0
[[2, 4, 7], [2, 4, 7], [2, 4, 7]]
1
1
[[2, 5, 7], [2, 5, 7], [2, 5, 7]]
1
2
[[2, 5, 8], [2, 5, 8], [2, 5, 8]]
2
0
[[3, 5, 8], [3, 5, 8], [3, 5, 8]]
2
1
[[3, 6, 8], [3, 6, 8], [3, 6, 8]]
2
2
[[3, 6, 9], [3, 6, 9], [3, 6, 9]]
[[3, 6, 9], [3, 6, 9], [3, 6, 9]]

因此,例如,循环的第一步。 j = 0 和 i = 0。但是,output[0][0]、output[1][0] 和 output[2][0] 都被循环改变了。这是为什么呢?????

我现在很迷茫。我用 Java 编写了相同的代码并且它运行正常。

public class TransposeMatrix {
    public static int[][] transpose(int[][] A) {
        int[][] result = new int[A[0].length][A.length];
        for (int j = 0; j < A[0].length; j++) {
            for (int i = 0; i < A.length; i++) result[j][i] = A[i][j];
        }
        return result;
    }
}

这个问题的链接是:https://leetcode.com/problems/transpose-matrix/

最佳答案

当你像这样在 python 中乘以列表时,你实际上并没有创建新列表,而是创建了对同一个列表的多个引用。因此,当您更改一个列表中的值时,您也会更改其他列表中的值。这就是为什么你的输出是 [[3,6,9], [3,6,9], [3,6,9]];它只是三个列表中的最后一个(即来自 for 循环的最后一个值)。

相反,您可以这样做:

def transpose(A):
    output = [['']* (len(A)) for y in range(len(A[0]))]
    # or: output = [['' for x in range(len(A))] for y in range(len(A[0]))]
    for j in range(len(A[0])):
        for i in range(len(A)):
            output[j][i] = A[i][j]
    return output

transpose([[1,2,3],[4,5,6],[7,8,9]])

返回 [[1,4,7],[2,5,8],[3,6,9]]

希望这对您有所帮助!

关于java - 来自 python 的转置矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55877231/

相关文章:

python - 如果Python中不存在全局变量,如何创建它?

python - 在Python中生成特定的列表组合

Java:你能解释一下这个简单的语句(System.out.println)吗?

c# - 找到最好的区间匹配结果

java - 删除字符串中特定位置的字符

python - pandas 中的字符串打印不正确

python - "relation already exists"在 odoo 中添加 Many2many 字段后

java - 并发修改异常

python-3.x - 如何使用 python 3.5 在 Google App Engine 中打开文件?

python-3.x - Python 3 - 将自定义 header 添加到 urllib.request 请求