python - Flatten (an irregular) list of lists -
Yes, I know that this topic is covered before (,,,,) but as far as I know, all solutions, except for one, fail in this type of list:
l = [[[1, 2, 3], [4, 5]], 6] where is the desired output
[1, 2, 3, 4, 5, 6] or Probably better, an Iterator I've seen that the only solution works for an arbitrary nest victim: <-> def flatten (x): Results = [] for X in L: if hasattr (a , "__iter__") and not isinstance (el, basestring): result.extend (flatten (el)) Other: result.append (el) Return result Flaton (L)
Is the best model? Did i ignore something Any problems?
Using generator functions can make reading a lesson easier and perhaps boost your performance. .
Python 2 Deaf Flaton (L): L for L: if not isestance (L, collection is notable) and is not (L, basestress): <3 python 3 in python 3 in Flaton (L) for the sub: yield sub: yield L
basestring is no longer there, but you can use a code of str and bytes to get the same effect. From the yielding operator returns an item from a generator at a time. It has been added to 3.3 def flatten (l): L for L: if isinstance (L, collections.Iterable) and not isinstance (L, (str, bytes)): Yield Flaton (L) Other: Yield L
Comments
Post a Comment