Is there a Python module that already does this?
David Eppstein
eppstein at ics.uci.edu
Wed Feb 6 12:44:03 EST 2002
In article <a3rbad$19u08k$1 at ID-98166.news.dfncis.de>, "MDK" <mdk at mdk.com>
wrote:
> For example:
>
> ("cat",5,['dog',[3,3,1]],"zoo")
>
> Would become:
>
> ('c','a','t',5,'d','o','g',3,3,1,'z','o','o')
This is standard in LISP as "flatten". Here's an implementation using
simple generators.
from __future__ import generators
def flatten(x):
def flatgen(x):
try:
xg = iter(x)
for y in xg:
if y == x:
# prevent infinite recursion
# when x is a character
yield x
return
yg = flatgen(y)
for z in yg:
yield z
except TypeError:
yield x
return tuple(flatgen(x))
print flatten(("cat",5,['dog',[3,3,1]],"zoo"))
('c', 'a', 't', 5, 'd', 'o', 'g', 3, 3, 1, 'z', 'o', 'o')
--
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