Boris Borcic wrote:
Rustom Mody wrote:
def fl1(l): return [y for x in l for y in x]
# recursive flatten
def fr(l):
... if not isinstance(l,list): return [l]
... return fl1([fr(x) for x in l])
For a short non-recursive procedure - not a function, modifies L in-place but
none of its sublists.
>>> def flatten(L) :
.... for k,_ in enumerate(L) :
.... while isinstance(L[k],list) :
.... L[k:k+1]=L[k]
flattens L to any depth, eg
>>> L=[1,[2,[3,4]],5,6,[[7],8]]
>>> flatten(L)
>>> L
[1, 2, 3, 4, 5, 6, 7, 8]
Mh, this will fail though if the last item (of the last item (of the...)) is an empty list, eg L=[[]]. If you
want to cover this case you can wrap the inside of the proc with a try except IndexError: pass, in which case
you can also simplify the enumerate(L) to an indefinite counter. Or insert a dummy value before starting and
pop it off at the end.
---
Ce courrier électronique ne contient aucun virus ou logiciel malveillant parce
que la protection avast! Antivirus est active.
http://www.avast.com
--
https://mail.python.org/mailman/listinfo/python-list