On Wed, 23 Jan 2008, William Stein wrote:
>
> On Jan 23, 2008 4:12 PM, Jason Grout <[EMAIL PROTECTED]> wrote:
>>
>> Does anyone know the best way to partition a list into sublists of a
>> specific length, similar to the Partition command in Mathematica? I'm
>> thinking of something like:
>>
>> sage: partition([1,2,3,4],2)
>> [[1,2],[3,4]]
>> sage: partition([1,2,3,4,5],2,pad=0)
>> [[1,2],[3,4],[5,0]]
>>
>> It seems like this is a problem that python would have solved millions
>> of years ago, but I can't find anything when searching online. I can
>> whip it up quickly, but I'm sure it's already been invented, which is
>> why I'm asking.
>
> Let me be the first of many to post a one liner:
>
> sage: def partition(v, n):
> ... return [v[n*i:n*i+n] for i in range(len(v)//n)]
>
> sage: partition([1,2,3,4],2)
> [[1, 2], [3, 4]]
Let me be the first of many to post a counterexample:
sage: partition([1,2,3,4,5],2)
[[1, 2], [3, 4]]
and a fix:
sage: def partition(v,n):
... return [v[i:i+n] for i in range(0,len(v),n)]
sage: partition([1,2,3,4,5],2)
[[1, 2], [3, 4], [5]]
--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to sage-devel@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at http://groups.google.com/group/sage-devel
URLs: http://www.sagemath.org
-~----------~----~----~----~------~----~------~--~---