Best pattern/idiom
Chris Connett
chrisccc_3k at yahoo.com
Tue Aug 10 10:18:13 EDT 2004
Michele Simionato wrote:
> Chris Connett <chrisccc_3k at yahoo.com> wrote in message news:<4117c3d8$1 at buckaroo.cs.rit.edu>...
>
>>I was wondering if there were a well known pattern/idiom for breaking a
>>sequence into a list of lists, each n elements long, e.g.
>>
>>[0,1,2,3,4,5,6,7,8,9,10,11] -> [[0,1,2,3],[4,5,6,7],[8,9,10,11]]
>>
>>This comes up reasonably often in my work, and every time I re-think
>>about it, and come up with
>>[ lis[n:n+4] for n in range( 0, len( lis ), 4 ) ]
>>which seems very kludgy to me, since it uses a range and len, 2 mentions
>>of the list identifier and 2 literal 4's (which is the size I want to
>>break into this time).
>>
>>Is there a better way?
>
>
> From a post of mine of some time ago ...
>
>
>>>>import itertools
>>>>def chop(it, n):
>
> ... tup = (iter(it),)*n
> ... return itertools.izip(*tup)
> ...
>
>>>>list(chop([1,2,3,4,5,6],3)) [(1, 2, 3), (4, 5, 6)]
>>>>list(chop([1,2,3,4,5,6],2)) [(1, 2), (3, 4), (5, 6)]
>>>>list(chop([1,2,3,4,5,6],1))
>
> [(1,), (2,), (3,), (4,), (5,), (6,)]
>
> Michele Simionato
That's slick! :) Though, objectively, it might be less maintainable,
since if I didn't know what it was doing, it'd take me a minute to
figure it out. I'll definitely keep that idea in my toolbox though!
More information about the Python-list
mailing list