Is there a Python module that already does this?
David Eppstein
eppstein at ics.uci.edu
Wed Feb 6 20:39:31 EST 2002
Here it is in a functional programming style:
import operator
def flatten(x):
if operator.isSequenceType(x) and (len(x) != 1 or x[0] != x):
return reduce(operator.concat, map(flatten, x), [])
else:
return [x]
print flatten(["cat",5,['dog',[3,3,1]],"zoo"])
...outputs...
['c', 'a', 't', 5, 'd', 'o', 'g', 3, 3, 1, 'z', 'o', 'o']
All that list copying makes it somewhat inefficient, though...
--
David Eppstein UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/
More information about the Python-list
mailing list