Recursively smooths a nested list in Python

I play a little with generators in Python and try to use a simple recursive scheme to implement the flatten function. That is, a function that takes as an input list a list that can contain labels, and displays iterable objects that are repeated only over atomic input elements.

So, print(list(flatten([1,2,3,[4,5,6]])))should return something containing [1,2,3,4,5,6].

My attempt is as follows:

def flatten(toflatten):
    try:
        for element in toflatten:
            flatten(element)
    except TypeError:
        yield toflatten

So, he has to check if his argument is an iterable object. If so, repeat this object as well. Otherwise, we get it as an atomic element.

This does not work, but flatten([1,2,3,[4,5,6]])simply returns an empty list.

Why is this so? And in particular; why doesn't it even make recursive function calls on this input? (I am using Python 3.5)

+3
1

, . , . .

  • try-except . , a TypeError , . , .

  • . . - . yield from, python3.3 +.

  • , except yield element, toflatten. .

def flatten(toflatten):    
   for element in toflatten:
       try:
           yield from flatten(element)
       except TypeError:
           yield element

,

>>> list(flatten([1,2,3,[4,5,6]]))
[1, 2, 3, 4, 5, 6]

EAFP ( , ), . ( , ), : .


: LYBL (Look Before You Leap). , , if, .

def flatten(toflatten):    
   for element in toflatten:
       if isinstance(element, list):
           yield from flatten(element)
       else:
           yield element

, ,

>>> list(flatten([1,2,3,[4,5,6]]))
[1, 2, 3, 4, 5, 6]

, yield from . , ?

>>> list(flatten([1,2,3,[4,5,'abc']]))
[1, 2, 3, 4, 5, 'abc']

, , . , flatten .

x = [1, 2, 3]
x.append(x)

flatten(x)

:

RuntimeError: maximum recursion depth exceeded
+6
source

Source: https://habr.com/ru/post/1692204/


All Articles