There's a good discussion on the python mailing list regarding flatten:

http://mail.python.org/pipermail/python-list/2005-July/330367.html

particularly, it's got a number of different implementations, and benchmarks.


On Thu, 28 Jun 2007, Hamptonio wrote:

>
> I often want to flatten nested lists, and such a command (like
> Mathematica's Flatten) does not seem to be present in sage.  I propose
> adding such a command into the misc.py.  I am appending some candidate
> code below, and I will also put it on sage-trac (http://
> www.sagemath.org:9002/sage_trac/ticket/395)
>
> Here's my function:
>
> def flatten(in_list, ltypes=(list, tuple)):
>    """
>    Flattens a nested list.
>
>    INPUT:
>        in_list -- a list or tuple
>        ltypes -- optional list of particular types to flatten
>
>    OUTPUT:
>        a flat list of the entries of in_list
>
>    EXAMPLES:
>        sage: flatten([[1,1],[1],2])
>        [1, 1, 1, 2]
>        sage: flatten((['Hi',2,vector(QQ,[1,2,3])],(4,5,6)))
>        ['Hi', 2, (1, 2, 3), 4, 5, 6]
>        sage: flatten((['Hi',2,vector(QQ,[1,2,3])],
> (4,5,6)),ltypes=(list, tuple,
> sage.modules.vector_rational_dense.Vector_rational_dense))
>        ['Hi', 2, 1, 2, 3, 4, 5, 6]
>    """
>    index = 0
>    new_list = [x for x in in_list]
>    while index < len(new_list):
>        if not new_list[index]:
>            new_list.pop(index)
>            continue
>        while isinstance(new_list[index], ltypes):
>            new_list[index : index + 1] = list(new_list[index])
>        index += 1
>    return new_list
>
>
> >
>



--~--~---------~--~----~------------~-------~--~----~
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