欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python 矩阵转置 transpose

程序员文章站 2024-03-22 11:17:22
...

* 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