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

S

Steven Bethard

> 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top