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 [email protected]
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/
-~----------~----~----~----~------~----~------~--~---