Transpose list of lists

前端 未结 12 1595
旧巷少年郎
旧巷少年郎 2020-11-21 13:33

Let\'s take:

l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

The result I\'m looking for is

r = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]


        
相关标签:
12条回答
  • 2020-11-21 13:37

    One way to do it is with NumPy transpose. For a list, a:

    >>> import numpy as np
    >>> np.array(a).T.tolist()
    [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
    

    Or another one without zip:

    >>> map(list,map(None,*a))
    [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
    
    0 讨论(0)
  • 2020-11-21 13:44

    Equivalently to Jena's solution:

    >>> l=[[1,2,3],[4,5,6],[7,8,9]]
    >>> [list(i) for i in zip(*l)]
    ... [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
    
    0 讨论(0)
  • 2020-11-21 13:44
    matrix = [[1,2,3],
              [1,2,3],
              [1,2,3],
              [1,2,3],
              [1,2,3],
              [1,2,3],
              [1,2,3]]
        
    rows = len(matrix)
    cols = len(matrix[0])
    
    transposed = []
    while len(transposed) < cols:
        transposed.append([])
        while len(transposed[-1]) < rows:
            transposed[-1].append(0)
    
    for i in range(rows):
        for j in range(cols):
            transposed[j][i] = matrix[i][j]
    
    for i in transposed:
        print(i)
    
    0 讨论(0)
  • 2020-11-21 13:44
        #Import functions from library
        from numpy import size, array
        #Transpose a 2D list
        def transpose_list_2d(list_in_mat):
            list_out_mat = []
            array_in_mat = array(list_in_mat)
            array_out_mat = array_in_mat.T
            nb_lines = size(array_out_mat, 0)
            for i_line_out in range(0, nb_lines):
                array_out_line = array_out_mat[i_line_out]
                list_out_line = list(array_out_line)
                list_out_mat.append(list_out_line)
            return list_out_mat
    
    0 讨论(0)
  • 2020-11-21 13:47
    import numpy as np
    r = list(map(list, np.transpose(l)))
    
    0 讨论(0)
  • 2020-11-21 13:48

    Maybe not the most elegant solution, but here's a solution using nested while loops:

    def transpose(lst):
        newlist = []
        i = 0
        while i < len(lst):
            j = 0
            colvec = []
            while j < len(lst):
                colvec.append(lst[j][i])
                j = j + 1
            newlist.append(colvec)
            i = i + 1
        return newlist
    
    0 讨论(0)
提交回复
热议问题