Posted By

iamok on 05/07/09


Tagged

lists


Versions (?)

grouping items in a sequence


 / Published in: Python
 

URL: http://drj11.wordpress.com/2009/01/28/my-python-dream-about-groups/#

  1. def g(l, n):
  2. return zip(*[iter(l)]*n)
  3.  
  4. '''
  5. >>> g(range(10), 3)
  6. [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
  7. >>> g('hello world!', 2)
  8. [('h', 'e'), ('l', 'l'), ('o', ' '), ('w', 'o'), ('r', 'l'), ('d', '!')]
  9.  
  10. Yeah, course. g groups a list l into a list of n-tuples, by taking each group of n elements from the list and making them into a tuple. How useful.
  11. '''

Report this snippet  

You need to login to post a comment.