Nested lists or conditional logic?

Peter Otten __peter__ at web.de
Wed Jan 28 17:14:07 EST 2004


Here's another odd one:

from itertools import islice

ITEMSINBATCH = 3;
ARBITRARYNUM = 11;

sample = ["item #%d" % i for i in range(ARBITRARYNUM)]

def batches(s, n):
    it = iter(s)
    n -= 1
    def batch(next):
        yield next
        for item in islice(it, n):
            yield item
    while True:
        yield batch(it.next())

for batch in batches(sample, ITEMSINBATCH):
    for item in batch:
        print item
    print "summary"

The client code is as clean as you can get...

Peter




More information about the Python-list mailing list