grouping items in a sequence


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  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. '''

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.