Matrix Transpose in Python

前端 未结 18 1529
甜味超标
甜味超标 2020-11-22 00:21

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\         


        
18条回答
  •  一个人的身影
    2020-11-22 00:56

    The problem with your original code was that you initialized transpose[t] at every element, rather than just once per row:

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

    This works, though there are more Pythonic ways to accomplish the same things, including @J.F.'s zip application.

提交回复
热议问题