簡體   English   中英

嵌套發電機和產量來自?

[英]Nested generators and yield from?

我有一個嵌套對象, a ,並希望在每個子容器上應用某種類型的過濾器:

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

保持嵌套結構但僅過濾偶數元素的函數如下所示:

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]]

不過,我想創建一個使用某種形式的嵌套同等發電機yield保持嵌套結構a

此,為了說明,正是我不想要的東西,因為它變平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]

我的理解是, Python 3.3中引入的 yield from可能允許嵌套保留傳遞對象的結構。 但顯然我誤解了:

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]]

您希望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]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM