smichr at hotmail.com
Thu Apr 7 14:00:38 CEST 2005
After posting the suggestion about splitting a string that contained a
quoted string, I looked back at my (at least I think it’s mine) flatten
routine and didn’t see anything like it at ASPN. Before I would post it
there, does anyone see any problems with this non-recursive approach?
I know that there are iterator approaches, but since the list already
exists is there any problem with flattening the whole thing? Or is part
of the problem that there may be iterable things that don’t need to be
completely “iterated to completion” before being able to yield the next
element? (Does that make sense?)
After searching for "Tim Peters flatten" I was able to find a similar
(It is in the basictypes folder in the latebind.py script by Mike C.
Fletcher.) It's so short, I post it for comparison. I'm not really sure
why there is a run through all possible indices rather than the ones
that exist in the given "inlist", though.
def flatten(inlist, type=type, ltype=(list,tuple), maxint= sys.maxint):
"""Flatten out a list, code developed by myself and modified by Tim
Peters, then by me again :)"""
# for every possible index
for ind in xrange( maxint):
# while that index currently holds a list
while isinstance( inlist[ind], ltype):
# expand that list into the index (and subsequent indicies)
inlist[ind:ind+1] = list(inlist[ind])
#ind = ind+1
’’’Flattens a list in place.’’’
while hasattr(l[i],“__iter__”): #used by some ASPN flatteners to
input: [1, 2, [3, 4, 5, [[6, 7], 8]], ’abc’, 9, [10, 11]]
output:[1, 2, 3, 4, 5, 6, 7, 8, ’abc’, 9, 10, 11]
More information about the Tutor