a sequence question

Roy Smith roy at panix.com
Fri Jan 28 15:27:17 CET 2005


In article <lzrKd.138680$K7.56500 at news-server.bigpond.net.au>,
 Chris Wright <wrightca at hotmail.com> wrote:

> Hi,
> 
> 1) I want to iterate over a list "N at a time"

You could do it with slicing and zip:

>>> l = [1, 2, 3, 4, 5, 6, 7, 8]
>>> zip (l[::2], l[1::2])
[(1, 2), (3, 4), (5, 6), (7, 8)]

To my eyes, that's a bit cryptic, but it works and it's certainly 
compact.  I don't use either zip() or extended slicing a lot; perhaps if 
I used them more often, the above would be more obvious to me if I read 
it in somebody else's code.

The interesting thing would be generalizing this to the "N at a time" 
case.  I think this works:

def nzip (list0, n):
    args = []
    for i in range(n):
        slice = list0[i::n]
        args.append (slice)
    return zip (*args)

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print nzip (l, 3)

Roy-Smiths-Computer:play$ ./nzip.py
[(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12)]

but I haven't given any thought to what happens if the length of the 
list isn't a multiple of n (exercise for the reader).  It's also 
annoying that the above generates a bunch of temporary lists.  It would 
be cool if there was a way to have the intermediates be generator 
expressions, but I'm not that good with that stuff, so I'll leave that 
as an exercise for other readers :-)



More information about the Python-list mailing list