python中矩阵的转置_Python中的矩阵转置

I am trying to create a matrix transpose function for python but I can't seem to make it work.

Say I have

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

and I want my function to come up with

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

So in other words, if I were to print this 2D array as columns and rows I would like the rows to turn into columns and columns into rows.

I made this so far but it doesn't work

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值