Matrix Transpose in Python

前端 未结 18 1205
甜味超标
甜味超标 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 01:01

    The "best" answer has already been submitted, but I thought I would add that you can use nested list comprehensions, as seen in the Python Tutorial.

    Here is how you could get a transposed array:

    def matrixTranspose( matrix ):
        if not matrix: return []
        return [ [ row[ i ] for row in matrix ] for i in range( len( matrix[ 0 ] ) ) ]
    
    0 讨论(0)
  • 2020-11-22 01:03
    def matrixTranspose(anArray):
      transposed = [None]*len(anArray[0])
    
      for i in range(len(transposed)):
        transposed[i] = [None]*len(transposed)
    
      for t in range(len(anArray)):
        for tt in range(len(anArray[t])):            
            transposed[t][tt] = anArray[tt][t]
      return transposed
    
    theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
    
    print matrixTranspose(theArray)
    
    0 讨论(0)
  • 2020-11-22 01:05

    This one will preserve rectangular shape, so that subsequent transposes will get the right result:

    import itertools
    def transpose(list_of_lists):
      return list(itertools.izip_longest(*list_of_lists,fillvalue=' '))
    
    0 讨论(0)
  • 2020-11-22 01:08

    Much easier with numpy:

    >>> arr = np.array([[1,2,3],[4,5,6],[7,8,9]])
    >>> arr
    array([[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]])
    >>> arr.T
    array([[1, 4, 7],
           [2, 5, 8],
           [3, 6, 9]])
    >>> theArray = np.array([['a','b','c'],['d','e','f'],['g','h','i']])
    >>> theArray 
    array([['a', 'b', 'c'],
           ['d', 'e', 'f'],
           ['g', 'h', 'i']], 
          dtype='|S1')
    >>> theArray.T
    array([['a', 'd', 'g'],
           ['b', 'e', 'h'],
           ['c', 'f', 'i']], 
          dtype='|S1')
    
    0 讨论(0)
  • 2020-11-22 01:08

    `

    def transpose(m):
        return(list(map(list,list(zip(*m)))))

    `This function will return the transpose

    0 讨论(0)
  • 2020-11-22 01:09
    #generate matrix
    matrix=[]
    m=input('enter number of rows, m = ')
    n=input('enter number of columns, n = ')
    for i in range(m):
        matrix.append([])
        for j in range(n):
            elem=input('enter element: ')
            matrix[i].append(elem)
    
    #print matrix
    for i in range(m):
        for j in range(n):
            print matrix[i][j],
        print '\n'
    
    #generate transpose
    transpose=[]
    for j in range(n):
        transpose.append([])
        for i in range (m):
            ent=matrix[i][j]
            transpose[j].append(ent)
    
    #print transpose
    for i in range (n):
        for j in range (m):
            print transpose[i][j],
        print '\n'
    
    0 讨论(0)
提交回复
热议问题