ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Iterator to return items N-at-a-time
Submitter: paul cannon (other recipes)
Last Updated: 2005/08/11
Version no: 1.0
Category: Algorithms

 

5 stars 1 vote(s)


Description:

Creates an iterator which returns N-tuples built from the incoming items from another iterator. Useful, for example, when you need items two at a time.

Source: Text Source

def group(iterator, count):
    itr = iter(iterator)
    while True:
        yield tuple([itr.next() for i in range(count)])


>>> group([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 2)
<generator object at 0xb7debcac>
>>> list(_)
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

>>> list(group([0, 1, 2, 3, 4, 5, 6], 2))
[(0, 1), (2, 3), (4, 5)]

>>> dataset = ['Nausori', 5, True, 'Namadi', 10, True, 'Lautoka', 8, False, 'Suva', 3, True]
>>> for place, value, truth in group(dataset, 3):
...   if truth:
...     print '%s: %s' % (place, value)
... 
Nausori: 5
Namadi: 10
Suva: 3

Discussion:

I have often needed to extract items from a sequence or iterator two or three at a time. This short function makes that simple.

In the event the incoming iterator runs out of items before there are enough to fill up an N-tuple, the partial tuple is discarded. (The StopIteration exception raised by itr.next() propogates through group() and shows up to the caller as if group() raised it, thereby causing iteration through group() to end.)



Add comment

Number of comments: 1

using itertools.imap(), Dug Song, 2006/01/29

import itertools

def group2(iterator, count):
    return itertools.imap(None, *([ iter(iterator) ] * count))
or just map(), if you want a partial last tuple to be filled out with None...
Add comment



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. IPy Notify

4. Changing return value ...

5. Quantum Superposition

6. Pickle objects under ...

7. Generalized delegates ...

8. Reorder a sequence (uses ...

9. Setting Win32 System ...

10. ObjectMerger




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.