仅使用for / while循环在Python中转换nxn Matrix

时间:2014-03-26 21:45:28

标签: python for-loop while-loop transpose matrix-transform

我想知道为什么我写的解决方案不起作用:

def transpose(sudoku):
    n = len(sudoku)
    l_tr = [0]*n
    k = 0
    tr_sudoku = [0]*n
    while k < n:
        tr_sudoku[k] = l_tr
        k = k+1  
    i = 0
    for i in range(len(sudoku)):
        j = 0
        for j in range(len(sudoku)):
            tr_sudoku[i][j] = sudoku[j][i]
            print j, i, tr_sudoku, sudoku[i][j]
        print tr_sudoku
return tr_sudoku

correct = [[1,2,3],[2,3,1],[3,1,2]]

print transpose(correct)

它输出以下错误解决方案:

0 0 [[1, 0, 0], [1, 0, 0], [1, 0, 0]] 1
1 0 [[1, 2, 0], [1, 2, 0], [1, 2, 0]] 2
2 0 [[1, 2, 3], [1, 2, 3], [1, 2, 3]] 3
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
0 1 [[2, 2, 3], [2, 2, 3], [2, 2, 3]] 2
1 1 [[2, 3, 3], [2, 3, 3], [2, 3, 3]] 3
2 1 [[2, 3, 1], [2, 3, 1], [2, 3, 1]] 1
[[2, 3, 1], [2, 3, 1], [2, 3, 1]]
0 2 [[3, 3, 1], [3, 3, 1], [3, 3, 1]] 3
1 2 [[3, 1, 1], [3, 1, 1], [3, 1, 1]] 1
2 2 [[3, 1, 2], [3, 1, 2], [3, 1, 2]] 2
[[3, 1, 2], [3, 1, 2], [3, 1, 2]]
[[3, 1, 2], [3, 1, 2], [3, 1, 2]]

帮助将不胜感激!感谢。

理想的正确解决方案:

correct = [[1,2,4],[2,3,4],[3,4,2]]

将是:

tr_correct = [[1,2,3],[2,3,4],[4,4,2]]

1 个答案:

答案 0 :(得分:2)

您可以使用zip轻松转置:

def transpose(sudoku):
    return list(map(list, zip(*sudoku)))

示例输出:

>>> correct = [[1,2,3],[2,3,1],[3,1,2]]
>>> transpose(correct)
[[1, 2, 3], [2, 3, 1], [3, 1, 2]]

最简单的&#34;手册&#34;方法是切换行和列:

def transpose_manually(sudoku):
    output = sudoku[:] # new grid the same size
    for r in range(len(sudoku)): # each row
        for c in range(len(sudoku[0])): # each column
            output[c][r] = sudoku[r][c] # switch
    return output