5 ms·
I sometimes use zip as a poor man's matrix transposition operator: >>> m = [(1,2,3), (4,5,6), (7,8,9)] >>> zip(*m) [(1, 4, 7), (2, 5, 8), (3, 6, 9)
by grifaton 14y ago
I sometimes use zip as a poor man's matrix transposition operator:
>>> m = [(1,2,3), (4,5,6), (7,8,9)]
>>> zip(*m)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
- christianmann 14y agoThat's pretty.
- mickeyp 14y agoIf you want to transpose a matrix-like list of lists, but the sizes don't all match up, you can use izip_longest from itertools and give it a fillvalue to "fill in" for the missing elements: >>> m = [(1,2,3), (4,5,6), (7, 8)] >>> zip(*m) [(1, 4, 7), (2, 5, 8)] # Wrong >>> from itertools import izip_longest >>> list(izip_longest(*m, fillvalue=None)) [(1, 4, 7), (2, 5, 8), (3, 6, None)]