interleaving dictionary values
Noah Rawlins
noah.rawlins at comcast.net
Tue Nov 21 19:27:02 EST 2006
j1o1h1n at gmail.com wrote:
> filter(None, - my brain parses that automatically now. This is not so
> bad. Flatten is snitched from ASPN/Cookbook/Python/Recipe/363051,
> thank you Jordan Callicoat, Mike C. Fletcher:
>
> def flatten(l, ltypes=(list, tuple)):
> i = 0
> while (i < len(l)):
> while (isinstance(l[i], ltypes)):
> l[i:i+1] = list(l[i])
> i += 1
> return l
>
On a side note, that version of flatten doesn't handle an empty list as
the last element of a list...
>>> flatten([1, 2, 3, []])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in flatten
IndexError: list index out of range
You need a try: in there or something...
def flatten(l, ltypes=(list, tuple)):
i = 0
while(i < len(l)):
try:
while(isinstance(l[i], ltypes)):
l[i:i+1] = list(l[i])
i += 1
except IndexError:
pass
return l
noah
More information about the Python-list
mailing list