Transpose list of lists

前端 未结 12 1786
旧巷少年郎
旧巷少年郎 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]]
    

提交回复
热议问题