小编典典

Python中的矩阵转置

python

我正在尝试为python创建矩阵转置函数,但似乎无法使其工作。说我有

theArray = [['a','b','c'],['d','e','f'],['g','h','i']]

我想提出我的职能

newArray = [['a','d','g'],['b','e','h'],['c', 'f', 'i']]

因此,换句话说,如果我要将此2D数组打印为列和行,我希望将行变成列,将列变成行。

我到目前为止已经做到了,但是没有用

def matrixTranspose(anArray):
    transposed = [None]*len(anArray[0])
    for t in range(len(anArray)):
        for tt in range(len(anArray[t])):
            transposed[t] = [None]*len(anArray)
            transposed[t][tt] = anArray[tt][t]
    print transposed

阅读 597

收藏
2020-02-12

共1个答案

小编典典

Python 2:

>>> theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
>>> zip(*theArray)
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]

Python 3:

>>> [*zip(*theArray)]
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
2020-02-12