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)
But I would like to create an equivalent generator that uses some form of nested yield
to 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))
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))
, (.. ), :
list(nested_generator(a))
# [[2], [4, 6], [8]]