DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Iterator To Return N Items At-a-time
Copied from paul cannon's recipe <a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439095>here</a>
def group(iterator, count): itr = iter(iterator) while True: yield tuple([itr.next() for i in range(count)])
After the above definition, you can use it very easily.
>>> list(group([0, 1, 2, 3, 4, 5], 2)) [(0, 1), (2, 3), (4, 5)] >>> dataset = ['Nausori', 5, 'Namadi', 10, 'Suva', 3] >>> for place, value in group(dataset, 2): ... print '%s: %s' % (place, value) ... Nausori: 5 Namadi: 10 Suva: 3
The above code is somewhat simplified. See the <a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439095>recipe</a> for full discussion.