William Stein wrote:
> On 10/26/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>>> which produces a nested list.  Is there a way to flatten the list by one
>>> or two levels, but not flatten it all the way?  Something like:
>>>
>>> sage: flatten([[[1,2],[3,4]],[[5,6],[7,8]]],1)
>>> [[1,2],[3,4],[5,6],[7,8]]
> 
> An easy way to do the above is the following:
> 
> sage: v = [[[1,2],[3,4]],[[5,6],[7,8]]]
> sage: sum(v, [])
> [[1, 2], [3, 4], [5, 6], [7, 8]]
> sage: sum(sum(v, []), [])
> [1, 2, 3, 4, 5, 6, 7, 8]
> 
> This is not a flatten-to-level 1 in general, but if you really want
> to do just things like the example above it does what you want.
> 
> William
> 
> > 
> 

I've modified the flatten.py function to deal with a max level of 
flatten.  It runs a little slower than the current flatten function (220 
microseconds instead of 170 microseconds on %timeit for a particular 
case), but I think the extra functionality is worth it.  If the time 
issue is a problem, we can just split the function into two branches 
depending on if a max_level is passed to the function.

I posted up the patch on ticket #1016.

I'm very curious how this compares to a recursive version.  The 
recursive version noted above and William's version using sum both choke 
when the depth of the list is not uniform (e.g., [[1,[2]],[3,4]] ).

With the patched version of flatten, you can restrict the flattening 
based on both the types of elements and the level at which the elements 
are located in the nested list.

Thanks,

Jason


--~--~---------~--~----~------------~-------~--~----~
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://sage.scipy.org/sage/ and http://modular.math.washington.edu/sage/
-~----------~----~----~----~------~----~------~--~---

Reply via email to