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
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.
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))]