"Stringizing" a list
Mike Fletcher
mfletch at tpresence.com
Wed Aug 9 15:15:49 EDT 2000
Something like
string.join(hyperCollapse( data))
Should be fairly fast and general.
Enjoy,
Mike
import copy, types, sys
from types import ListType, TupleType # this now only supports the obsolete
stuff...
def hyperCollapse( inlist, allowedmap, type=type, list=list,
itype=types.InstanceType, maxint= sys.maxint):
'''
Destructively flatten a mixed hierarchy to a single level.
Non-recursive, many speedups and obfuscations by Tim Peters :)
'''
try:
# for every possible index
for ind in xrange( maxint):
# while that index currently holds a list
expandable = 1
while expandable:
expandable = 0
if allowedmap.has_key( type(inlist[ind]) ):
# expand that list into the index
(and subsequent indicies)
inlist[ind:ind+1] = list(
inlist[ind])
expandable = 1
# alternately you could iterate through
checking for isinstance on all possible
# classes, but that would be very slow
elif type( inlist[ind] ) is itype and
allowedmap.has_key( inlist[ind].__class__ ):
# here figure out some way to
generically expand that doesn't risk
# infinite loops...
templist = []
for x in inlist[ind]:
templist.append( x)
inlist[ind:ind+1] = templist
expandable = 1
except IndexError:
pass
return inlist
-----Original Message-----
From: cg at gaia.cdg.acriter.nl [mailto:cg at gaia.cdg.acriter.nl]
Sent: Wednesday, August 09, 2000 5:42 AM
To: python-list at python.org
Subject: "Stringizing" a list
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.
--
Cees de Groot http://www.cdegroot.com <cg at cdegroot.com>
GnuPG 1024D/E0989E8B 0016 F679 F38D 5946 4ECD 1986 F303 937F E098 9E8B
Forge your CipherSaber and list it: http://www.xs4all.nl/~cg/ciphersaber/
--
http://www.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list