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
3 回答
Qyouu
TA贡献1786条经验 获得超11个赞
>>> theArray = [['a','b','c'],['d','e','f'],['g','h','i']]>>> zip(*theArray)[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
>>> [*zip(*theArray)][('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
添加回答
举报
0/150
提交
取消