Nested generators and exit?

I have a nested object a, and you want to apply some kind of filter to each of its subcontainers:

a = [[1, 2], [3, 4, 5, 6], [7, 7, 8]]

The function of saving the nested structure, but the filter only for even elements will look like this:

def nested_filter(obj):
    res = []
    for sub_obj in obj:
        even = [i for i in sub_obj if i % 2 == 0]
        res.append(even)
    return res

nested_filter(a)
# [[2], [4, 6], [8]]

But I would like to create an equivalent generator that uses some form of nested yieldto support a nested structure a.

This, for illustration, is exactly what I don't want, because it smooths out a:

def nested_yield(obj):
    """Will flatten the nested structure of obj."""
    for sub_obj in obj:
        for i in sub_obj:
            if i % 2 == 0:
                yield i

list(nested_yield(a))
# [2, 4, 6, 8]

My understanding was that yield from, introduced in Python 3.3 , it can allow an attachment that preserves the structure of the passed object. But, apparently, I misinterpret:

def gen1(obj):
    for sub_obj in obj:
        yield from gen2(sub_obj)


def gen2(sub_obj):
    for i in sub_obj:
        if i % 2 == 0:
            yield i

list(gen1(a))
# [2, 4, 6, 8]

, (.. ), :

list(nested_generator(a))
# [[2], [4, 6], [8]]
+4
1

, nested_generator . .

, - :

>>> def nested_filter(L):
    for l in L:
        yield [i for i in l if i % 2 == 0]


>>> a = [[1, 2], [3, 4, 5, 6], [7, 7, 8]]
>>> list(nested_filter(a))
[[2], [4, 6], [8]]

-, , , yield:

>>> def generator_filter(L):
    for n in L:
        if n % 2 == 0:
            yield n


>>> def nested_filter(L):
    for l in L:
        yield list(generator_filter(l))


>>> a = [[1, 2], [3, 4, 5, 6], [7, 7, 8]]
>>> list(nested_generator(a))
[[2], [4, 6], [8]]
+2

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


All Articles