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

回答:

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')]

以上是 Python中的矩阵转置 的全部内容, 来源链接: utcz.com/qa/418094.html

回到顶部