a sequence question

Steven Bethard steven.bethard at gmail.com
Tue Feb 1 01:53:54 EST 2005


Nick Coghlan wrote:
> I'd definitely recommend hiding this trick inside a function. Perhaps 
> something like (using Michael's function name):
> 
> from itertools import izip, repeat, chain
> 
> def partition(seq, part_len):
>   return izip(*((iter(seq),) * part_len))
> 
> def padded_partition(seq, part_len, pad_val=None):
>   itr = iter(seq)
>   if (len(seq) % part_len != 0):
>     padding = repeat(pad_val, part_len)
>     itr = chain(itr, padding)
>   return izip(*((itr,) * part_len))

I think you can write that second one so that it works for iterables 
without a __len__:

py> def padded_partition(iterable, part_len, pad_val=None):
...     itr = itertools.chain(
...         iter(iterable), itertools.repeat(pad_val, part_len - 1))
...     return itertools.izip(*[itr]*part_len)
...
py> list(padded_partition(itertools.islice(itertools.count(), 10), 2))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
py> list(padded_partition(itertools.islice(itertools.count(), 10), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]

I just unconditionally pad the iterable with 1 less than the partition 
size...  I think that works right, but I haven't tested it any more than 
what's shown.

Steve



More information about the Python-list mailing list