The problem of P121 in the basic course of Python about the generator dealing with multi-layer nested lists

the following is a routine in the book:

def flatten(nested):
    try:
        -sharp 
        try:
            nested + ""
        except TypeError:
            pass
        else:
            raise TypeError

        for sublist in nested:
            for element in flatten(sublist):
                yield element
    except TypeError:
        yield nested


a = list(flatten([[[1], "abc"], 3, 4, [5, [6, 7]], [[[8, 9, 10], 11], 12], 13, 14]))
print(a)
pycharmraise TypeErrorraise SyntaxErrorTypeError...
Mar.07,2021

The

program is right, and the example given is also correct. I don't think the above program should report an error.
the meaning of the flatten function is to iterate the tree structure according to the order of depth priority. It is possible to "squash" a tree structure into a list structure.
for example:

        -sharp 
        try:
            nested + ''
        except TypeError:
            pass
        else:
            raise TypeError
The

comment indicates that the string object is not iterated. If this paragraph is missing, the program will fall into an infinite loop when it encounters a string in the iterative object. This is because strings are also iterable objects.

for example, enter 'abc' , then the inner layer try statement of the original function will raise TypeError . This TypeError is captured by the outer try statement except TypeError , and then ' abc' is directly output as an iterative result.
if you enter an uniterable object, such as nested +', it will be because of except TypeError when executing except TypeError . Continue to execute for sublist in nested , but 123 is an int type, not an iterable object, so TypeError: 'int' object is not iterable is thrown. This error is also caught by the outer try statement, and 123 is output as an iteration result.
only iterable objects that are not strings are entered into for sublist in nested .

if the try statement is missing, for sublist in nested: is executed, where nested is 'abc' , then it iterates over ' a', 'baked,' c', and returns 'a' when iterating to 'a'. Because 'a' is iterable again, it returns again. In this way, the program will fall into an infinite loop that iterates through 'a', and finally throws RecursionError .

so there is no problem with the design of the flatten function. It accomplishes the function that the designer expects it to achieve.

Menu