Skip to main content
 首页 » 编程设计

python之生成器未按预期运行

2025年05月04日11sharpest

我是生成器的新手。当我将 print 替换为 yield 时,为什么第一个带有 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') 

然后是不给出所有组合的生成器

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') 

请您参考如下方法:

虽然 print 从您所在的任何嵌套调用中打印,但生成器仅从第一层产生。如果你需要“调用生成器”来获得更多的值来产生,你必须使用内部生成器的值并将它们产生出来,如下所示:

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 

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

注意:在 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_)