Hacker Timesnew | past | comments | ask | show | jobs | submitlogin

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


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


That's pretty.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: