python 矩阵转置 transpose

* for in 嵌套列表

def transpose1(matrix):
    cols = len(matrix[0])
    return [[row[i] for row in matrix] for i in range(0,cols)]


def transpose2(matrix):
    transposed = []
    for i in range(len(matrix[0])):
        transposed.append([row[i] for row in matrix])
    return transposed


def transpose3(matrix):
    transposed = []
    for i in range(len(matrix[0])):
        transposed_row = []
        for row in matrix:
            transposed_row.append(row[i])
        transposed.append(transposed_row)
    return transposed

 

test:

matrix = [
    [1,2,3,4],
    [5,6,7,8],
    [9,10,11,12]
]
print(transpose1(matrix))
print(transpose2(matrix))
print(transpose3(matrix))

output:

[Running] python -u "j:\python\matrix.py"

[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

 

[Done] exited with code=0 in 0.125 seconds

你可能感兴趣的:(python)