how to make ["a","b",["c","d"],"e"] into ['a', 'b', 'c', 'd', 'e'] ?

Boris Borcic bborcic at gmail.com
Thu Apr 10 10:14:55 EDT 2014


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]


---
Ce courrier électronique ne contient aucun virus ou logiciel malveillant parce que la protection avast! Antivirus est active.
http://www.avast.com





More information about the Python-list mailing list