python matrix transpose and zip

后端 未结 6 1119
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 11:32

How to get the transpose of this matrix..Any easier ,algorithmic way to do this...

1st question:

 Input  a=[[1,2,3],[4,5,6],[7,8,9]]
 Expected outpu         


        
相关标签:
6条回答
  • 2020-11-30 11:47

    You can use list(zip(*a)).

    By using *a, your list of lists can have any number of entries.

    0 讨论(0)
  • 2020-11-30 11:49

    You can use numpy.transpose

    numpy.transpose

    >>> import numpy
    >>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    >>> numpy.transpose(a)
    array([[1, 4, 7],
           [2, 5, 8],
           [3, 6, 9]])
    
    0 讨论(0)
  • 2020-11-30 11:57

    Try this replacing appropriate variable

    import numpy as np
    
    data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))
    
    data_transpose = np.transpose(data) # replace with your code
    print(data_transpose)
    
    0 讨论(0)
  • 2020-11-30 12:04

    Use zip(*a):

    >>> zip(*a)
    [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
    

    How it works: zip(*a) is equal to zip(a[0], a[1], a[2]).

    0 讨论(0)
  • 2020-11-30 12:07

    Solution is to use tuple() function.

    Here is an example how to do that in your case :

    a      = [[1,2,3],[4,5,6],[7,8,9]]
    output = tuple(zip(*a))
    
    print(output)
    
    0 讨论(0)
  • 2020-11-30 12:08

    question answers:

    >>> import numpy as np
    >>> first_answer = np.transpose(a)
    >>> second_answer = [list(i) for i in zip(*a)]
    

    thanks to afg for helping out

    0 讨论(0)
提交回复
热议问题