gpt4 book ai didi

python - Python中的矩阵转置

转载 作者:IT老高 更新时间:2023-10-28 12:31:14 27 4
gpt4 key购买 nike

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

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

我希望我的功能能够提出

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

换句话说,如果我要将这个二维数组打印为列和行,我希望行变成列,列变成行。

到目前为止我做了这个,但它不起作用

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 - Python中的矩阵转置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4937491/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com