Transpose list of lists

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

    Three options to choose from:

    1. Map with Zip

    solution1 = map(list, zip(*l))
    

    2. List Comprehension

    solution2 = [list(i) for i in zip(*l)]
    

    3. For Loop Appending

    solution3 = []
    for i in zip(*l):
        solution3.append((list(i)))
    

    And to view the results:

    print(*solution1)
    print(*solution2)
    print(*solution3)
    
    # [1, 4, 7], [2, 5, 8], [3, 6, 9]
    

提交回复
热议问题