wishlist item: itertools.partition (WAS: Wishlist item: itertools.flatten)

Steven Bethard steven.bethard at gmail.com
Sat Mar 12 20:50:03 CET 2005


gene.tani at gmail.com wrote:
 > window / cons / fencepost / slice functions: +1
 >
 > (with a flag to say if you want to truncate or pad incomplete tuples
 > at end of input sequence.
 >
 > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303279
 > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303060
 > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347689
 >
 > Probably more recipes in there, (and not CPAN-ish yet) but multiple
 > submissions bespeak a certain need, i think.

Yes, also worth noting is the thread:

http://mail.python.org/pipermail/python-list/2005-January/263004.html

which concludes with:

from itertools import islice, chain, repeat

def partition(iterable, part_len):
      itr = iter(iterable)
      while 1:
          item = tuple(islice(itr, part_len))
          if len(item) < part_len:
              raise StopIteration
          yield item

def padded_partition(iterable, part_len, pad_val=None):
      padding = repeat(pad_val, part_len-1)
      itr = chain(iter(iterable), padding)
      return partition(itr, part_len)

STeVe



More information about the Python-list mailing list