Python List Comprehensions - Transposing

前端 未结 2 891
误落风尘
误落风尘 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.

提交回复
热议问题