Matrix Transpose in Python

前端 未结 18 1229
甜味超标
甜味超标 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:55
    >>> theArray = [['a','b','c'],['d','e','f'],['g','h','i']]
    >>> [list(i) for i in zip(*theArray)]
    [['a', 'd', 'g'], ['b', 'e', 'h'], ['c', 'f', 'i']]
    

    the list generator creates a new 2d array with list items instead of tuples.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 00:59

    If your rows are not equal you can also use map:

    >>> uneven = [['a','b','c'],['d','e'],['g','h','i']]
    >>> map(None,*uneven)
    [('a', 'd', 'g'), ('b', 'e', 'h'), ('c', None, 'i')]
    

    Edit: In Python 3 the functionality of map changed, itertools.zip_longest can be used instead:
    Source: What’s New In Python 3.0

    >>> import itertools
    >>> uneven = [['a','b','c'],['d','e'],['g','h','i']]
    >>> list(itertools.zip_longest(*uneven))
    [('a', 'd', 'g'), ('b', 'e', 'h'), ('c', None, 'i')]
    
    0 讨论(0)
  • 2020-11-22 00:59

    you can try this with list comprehension like the following

    matrix = [['a','b','c'],['d','e','f'],['g','h','i']] n = len(matrix) transpose = [[row[i] for row in matrix] for i in range(n)] print (transpose)

    0 讨论(0)
  • 2020-11-22 00:59
    a=[]
    def showmatrix (a,m,n):
        for i in range (m):
            for j in range (n):
                k=int(input("enter the number")
                a.append(k)      
    print (a[i][j]),
    
    print('\t')
    
    
    def showtranspose(a,m,n):
        for j in range(n):
            for i in range(m):
                print(a[i][j]),
            print('\t')
    
    a=((89,45,50),(130,120,40),(69,79,57),(78,4,8))
    print("given matrix of order 4x3 is :")
    showmatrix(a,4,3)
    
    
    print("Transpose matrix is:")
    showtranspose(a,4,3)
    
    0 讨论(0)
  • 2020-11-22 01:00
    def transpose(matrix):
       x=0
       trans=[]
       b=len(matrix[0])
       while b!=0:
           trans.append([])
           b-=1
       for list in matrix:
           for element in list:
              trans[x].append(element)
              x+=1
           x=0
       return trans
    
    0 讨论(0)
提交回复
热议问题