Python程序教程

您现在的位置是:首页 >  Python

当前栏目

python 矩阵转置 transpose

python,矩阵,转置,transpose
2025-03-28 09:01:09 时间

大家好,又见面了,我是你们的朋友全栈君。

* 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

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/137109.html原文链接:https://javaforall.cn