【问题标题】:Python yield: return or access other values computed within a generatorPython yield:返回或访问在生成器中计算的其他值
【发布时间】:2017-10-02 20:20:54
【问题描述】:

我想在生成器产生其他东西时跟踪某些值(比如计数、统计信息)。我目前的方法是将可变对象传递给生成器。用“return”返回这些值似乎不起作用。我很好奇是否有其他方法可以做到这一点。

在以下示例中,生成器从当前脚本生成代码行,并且字典跟踪器还跟踪计数:

import sys

def gen_lines_of_code(tracker):
    loc = 0
    with open(sys.argv[0]) as fp:
        for line in fp:
            if len(line.strip()) > 0:
                loc += 1
                yield line

    tracker["count"] = loc

# Dictionary to keep track of count of lines of code
track = {"count": 0}

g = gen_lines_of_code(track)

for v in g:
    print(v, end="")

print(f"\n\tLines of code in {sys.argv[0]}: {track['count']}")

【问题讨论】:

    标签: python-3.x generator return-value yield


    【解决方案1】:

    产生由 line 和 loc 组成的元组怎么样?

    import io
    
    def gen_lines_of_code(file):
        loc = 0
        for line in file:
            if line.strip():
                loc += 1
                yield line, loc
    
    file = io.StringIO("""
    Lorem ipsum dolor sit amet, consectetur adipiscing elit,
    sed do eiusmod tempor incididunt ut labore et dolore magna
    aliqua.
    
    Ut enim ad minim veniam, quis nostrud exercitation ullamco
    laboris nisi ut aliquip ex ea commodo consequat.
    """)
    
    g = gen_lines_of_code(file)
    
    for v, loc in g:
        print(v, end='')
    
    try:
        print("\n\tLines of code:", loc)
    except NameError:
        loc = 0
        print("\n\tLines of code:", loc)
    

    或者您可以使用可迭代类(使用__iter__ 方法):

    class GenLinesOfCode:
    
        def __init__(self, file):
            self.file = file
            self.loc = 0
    
        def __iter__(self):
            for line in self.file:
                if line.strip():
                    self.loc += 1
                    yield line
    
    
    g = GenLinesOfCode(file)
    
    for v in g:
        print(v, end='')
    
    print("\n\tLines of code:", g.loc)
    

    【讨论】:

    • 由于来自图书馆的消费者,可以产生什么是有限制的。
    • 具有可迭代类的第二个变体是否有效?如果它必须是一个迭代器,你也可以给它一个 __next__ 方法。
    猜你喜欢
    • 2015-09-11
    • 2015-06-07
    • 2017-04-29
    • 2019-12-01
    • 1970-01-01
    • 2022-11-08
    • 2021-04-07
    • 2019-04-17
    • 2011-06-25
    相关资源
    最近更新 更多