"Stringizing" a list
Alex Martelli
alex at magenta.com
Wed Aug 9 09:38:31 EDT 2000
"Cees de Groot" <cg at gaia.cdg.acriter.nl> wrote in message
news:8mr91p$g7e$1 at gaia.cdg.acriter.nl...
> I'm sure I've seen a place with a snippet for this, but I couldn't find
it:
>
> what's the cleanest way to convert a random nested list structure like:
>
> ['foo', ['bar', 'baz'], 'quux']
>
> into:
>
> 'foo bar baz quux' ?
>
> I've, ahem, solved this with a bit of recursion and relying on '+' to
throw
> in certain circumstances, but it's a hairy and ugly piece of code.
What about (the simplest idea that comes to mind, I'll admit):
from types import ListType
def flatten(alist):
result=[]
for element in alist:
if type(element)==ListType:
result.extend(flatten(element))
else:
result.append(element)
return result
import string
print string.join(flatten(['foo', ['bar', 'baz'], 'quux']))
I'm sure there must be something cleverer, but...
Alex
More information about the Python-list
mailing list