如何 return 矩阵列作为 Python 中的列表

How to return matrix columns as lists in Python

假设我有以下矩阵:

matrix = [[1,2,3], 
          [4,5,6], 
          [7,8,9]]

如何在不使用快捷方式的情况下创建一个函数,使 returns 列如下表所示的列表?提前致谢。

new_matrix = [[1,4,7], 
              [2,5,8], 
              [3,6,9]]

使用这个功能:

def matrixcolumns(matrix):
    out = []
    for i in range(len(matrix[0])):
        out.append([])
        for j in matrix:
            out[i].append(j[i])
    return out

我认为“没有捷径”是指使用 numpy.transpose 或其他库。如果不使用这些,您实际上可以通过压缩矩阵 list(zip(*matrix)) 的行来获得列表列表的转置。这将为您提供元组的转置列表。然后您可以迭代并将元组转换回列表。

试试这个 -

new_matrix = [list(i) for i in zip(*matrix)]
new_matrix


##### OR #####
## new_matrix = list(map(list,zip(*matrix)))
[[1, 4, 7], 
 [2, 5, 8], 
 [3, 6, 9]]

“快捷方式”可能是 np.array(matrix).T,但这将需要多种数据类型转换。