a sequence question

Nick Coghlan ncoghlan at iinet.net.au
Sat Feb 12 20:52:59 EST 2005


David Isaac wrote:
> "Nick Coghlan" <ncoghlan at iinet.net.au> wrote in message
> news:mailman.2434.1108179260.22381.python-list at python.org...
> 
>>A bug report on Sourceforge would help in getting the problem fixed for
> 
> the 2.5
> 
>>docs
> 
> 
> Done.

Bug 1121416, for anyone else interested. Looks Raymond agrees with me about the 
left-to-right evaluation of iterables being an overspecification.

Anyway, that means the zip and izip based solutions are technically version and 
implementation specific. Fortunately, the final versions are fairly easy to turn 
into a custom generator that doesn't rely on izip:

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)

Py> list(partition(range(10), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
Py> list(padded_partition(range(10), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
Py> list(padded_partition(range(10), 3, True))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, True, True)]

Well spotted on the fact that the way we were using zip/izip was undocumented, 
btw :)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list