joining list elements
Mike Fletcher
mfletch at tpresence.com
Sat Oct 14 01:15:44 EDT 2000
Hmm, from an old thread, I _think_ this was the best we came up with (note,
despite the doc string, the weird stuff is mostly my fault)...
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
Here's a less crufty version for just hierarchies of lists...
def collapse(inlist, type=type, ltype=types.ListType, maxint= sys.maxint):
'''
Destructively flatten a list hierarchy to a single level.
Non-recursive, and (as far as I can see, doesn't have any
glaring loopholes).
Further speedups and obfuscations by Tim Peters :)
'''
try:
# for every possible index
for ind in xrange( maxint):
# while that index currently holds a list
while type(inlist[ind]) is ltype:
# expand that list into the index (and
subsequent indicies)
inlist[ind:ind+1] = inlist[ind]
#ind = ind+1
except IndexError:
pass
return inlist
Enjoy yourself,
Mike
-----Original Message-----
From: johannes at zellner.org [mailto:johannes at zellner.org]
Sent: Friday, October 13, 2000 11:45 PM
To: python-list at python.org
Subject: joining list elements
Hi again,
how do I join list elements ?
e.g. I want [[1, 2, 3], [4, 5, 6]] --> [1, 2, 3, 4, 5, 6]
and [[1, 2, 3], 4, 5, 6 ] --> [1, 2, 3, 4, 5, 6]
and [1, 2, 3], 4 --> [1, 2, 3, 4]
any help much appreciated!
--
Johannes
--
http://www.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list