生成器的行为不符合预期

Tom*_*ivy 1 python function generator

我是发电机的新手.当我用yield替换print时,为什么print语句的第一个正确函数不起作用(Python 2.7)

首先是正确的打印功能:

def make_all_pairs(list_):
    pivot = list_.pop(0)
    for el in list_:
        pair = (pivot, el)
        print pair
    if len(list_) > 1:
        make_all_pairs(list_)      

make_all_pairs(["a","b","c","d","e"])

('a', 'b')  
('a', 'c')  
('a', 'd')  
('a', 'e')  
('b', 'c')  
('b', 'd')  
('b', 'e')  
('c', 'd')  
('c', 'e')  
('d', 'e')
Run Code Online (Sandbox Code Playgroud)

然后发电机不给出所有组合

def make_all_pairs(list_):
    pivot = list_.pop(0)
    for el in list_:
        pair = (pivot, el)
        yield pair
    if len(list_) > 1:
        make_all_pairs(list_)

x = make_all_pairs(["a","b","c","d","e"])
for el in x:
    print el

('a', 'b')
('a', 'c')
('a', 'd')
('a', 'e')
Run Code Online (Sandbox Code Playgroud)

Jan*_*sky 5

虽然print版画无论从任何呼叫的嵌套你在,发电机只能从第一级屈服.如果你需要"调用generator"来获得更多的值,你必须使用内部生成器中的值并将它们输出,如下所示:

def make_all_pairs(list_):
    pivot = list_.pop(0)
    for el in list_:
        pair = (pivot, el)
        yield pair
    if len(list_) > 1:
        for itm in make_all_pairs(list_):
            yield pair

x = make_all_pairs(["a","b","c","d","e"])
for el in x:
    print el
Run Code Online (Sandbox Code Playgroud)

警告:虽然代码现在产生更多值,但我不保证,结果是正确的.代码只显示如何处理内生成器生成的值.

注意:在python 3中,您可以使用替代构造 yield from

def make_all_pairs(list_):
    pivot = list_.pop(0)
    for el in list_:
        pair = (pivot, el)
        yield pair
    if len(list_) > 1:
        yield from make_all_pairs(list_)
Run Code Online (Sandbox Code Playgroud)

  • @TomKivy不,嵌套生成器很好,只需要正确处理(一旦你得到它就没有魔力). (2认同)