Python List Comprehensions - Transposing

前端 未结 2 888
误落风尘
误落风尘 2021-01-23 12:45

I\'m just starting out with list comprehensions by the reading the matrix transposing tutorial here. I understand the example, but I\'m trying to figure out a way to transpose t

相关标签:
2条回答
  • 2021-01-23 13:26

    Assuming all sub lists have the same number of elements:

    s = len(matrix[0])
    lcomp = [[row[i] for row in matrix] for i in range(s)]
    

    For sublists with mismatching lengths:

    s = len(max(matrix, key=len))
    

    On a side note, you could easily transpose your matrix with zip:

    matrix_T = zip(*matrix) # wrap with list() for Python 3
    

    Or use itertools.izip_longest for sublists with mismatching lengths.

    0 讨论(0)
  • 2021-01-23 13:40

    You can use another comprehension! They're a very powerful tool.

    [[row(i) for row in matrix] for i in range(max(len(r) for r in matrix))]
    
    0 讨论(0)
提交回复
热议问题