【问题标题】:Function to combine Python3 generator and instantiation结合 Python3 生成器和实例化的函数
【发布时间】:2019-06-23 15:50:26
【问题描述】:

我编写了一个生成器函数,我将其实例化,然后一遍又一遍地调用,每次都会增加数字。

def pagecnt():
    n = 1
    while True:
        yield n
        n += 1

pg = pagecnt()
print(next(pg))
print(next(pg))
print(next(pg))

这会打印 1、2 和 3。有没有办法将生成器和实例化组合成一个新函数,以便我可以调用

print(newfunc())
print(newfunc())
print(newfunc())

得到 1、2 和 3?

编辑:我不想只调用 3 次。它用于生成页码。所以我事先不知道我要调用它多少次。在每次调用之间,有很多代码来计算和生成图表。

【问题讨论】:

  • def newfunc(): return next(pg)?

标签: python python-3.x generator


【解决方案1】:

只需创建一个函数来实例化您的生成器并调用next n 次

def combine_func(n):
    pg = pagecnt()
    for _ in range(n):
        print(next(pg))

或者我们可以定义一个包装函数,它接收生成器实例,并返回一个我们可以调用以获取下一个元素的函数

def combine_func(pg):

    def next_elem():
        return next(pg)

    return next_elem

pg = pagecnt()
cf = combine_func(pg)
print(cf())
print(cf())
print(cf())

【讨论】:

    【解决方案2】:

    您可以创建一个简单的 Counter 类并定义 __call__()

    class Counter():
        def __init__(self):
            self.count = 0
        def __call__(self):
            self.count += 1
            return self.count
    
    c = Counter()
    print(c())
    print(c())
    print(c())
    

    打印:

    1
    2
    3
    

    您还可以在闭包中捕获迭代器并返回一个 lambda 函数:

    from itertools import count
    
    def Counter():
        it = count(1)
        return lambda: next(it)
    
    c = Counter()
    print(c())
    print(c())
    print(c())
    

    打印与上面相同。在这两种情况下,如果您想从 0 以外的地方开始,则很容易传入起始值。

    编辑:

    这与使用 count 相同,但使用自定义生成器:

    def Counter():
        def pagecnt():
            n = 1
            while True:
                yield n
                n += 1
        it = pagecnt()
        return lambda: next(it)
    
    c = Counter()
    print(c())
    print(c())
    print(c())
    

    【讨论】:

    • 我真的希望用发电机来做。我可以用自己的生成器替换 itertools 吗?
    • @Alpha8 -- 如果您愿意,可以直接用 pagecnt 函数替换 count
    • @MarkMeyer 您正在使用 c = Counter() 进行实例化。我们可以将它合并到 Counter() 代码中吗?
    • @Alpha8,不是真的。您需要某种方式来维护状态,这意味着该函数需要创建一些东西并返回一个可调用对象。如果一切都在函数内部,则每次调用都将重新开始。
    猜你喜欢
    • 2018-01-19
    • 1970-01-01
    • 2015-06-28
    • 2019-05-10
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    相关资源
    最近更新 更多