Transpose list of lists

前端 未结 12 1598
旧巷少年郎
旧巷少年郎 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:53

    Here is a solution for transposing a list of lists that is not necessarily square:

    maxCol = len(l[0])
    for row in l:
        rowLength = len(row)
        if rowLength > maxCol:
            maxCol = rowLength
    lTrans = []
    for colIndex in range(maxCol):
        lTrans.append([])
        for row in l:
            if colIndex < len(row):
                lTrans[colIndex].append(row[colIndex])
    

提交回复
热议问题