【问题标题】:Python how to partially consume an iterable generator (without `next`)?Python如何部分使用可迭代的生成器(没有`next`)?
【发布时间】:2020-11-14 19:29:40
【问题描述】:

我有一个作为可迭代生成器的类(根据Best way to receive the 'return' value from a python generator),我想通过for 循环部分使用它。

我不能使用next(如Python -- consuming one generator inside various consumers),因为第一次部分消费使用了一个只接受迭代器的库。如何从库函数停止的地方继续使用生成器?

(相关:Pause Python GeneratorIs there a way to 'pause' or partially consume a generator in Python, then resume consumption later where left off?

class gen(): # https://stackoverflow.com/q/34073370
    def __iter__(self):
        for i in range(20):
            yield i

# I want to partially consume in the first loop and finish in the second
my_gen_2 = gen()
for i in my_gen_2:  # imagine this is the internal implementation of the library function
    print(i)
    if i > 10:      # the real break condition is when iterfzf recieves user input
        break

for i in my_gen_2:  # i'd like to process the remaining elements instead of starting over
    print('p2', i)

# the confusion boils down to this
my_gen = gen()
for i in my_gen:
    print(i)    # prints 1 through 20 as expected
for i in my_gen:
    print('part two', i)    # prints something, even though the generator should have been "consumed"?

【问题讨论】:

    标签: python iterator generator


    【解决方案1】:

    每次你在循环中迭代生成器,你都会得到一个新的迭代器。 例如:

    class gen(): # https://stackoverflow.com/q/34073370
        def __init__(self):
            self.count = 0
        def __iter__(self):
            self.count += 1
            print("Hallo iter {0}".format(self.count))
            yield self.count
    
    

    my_gen = gen()
    >>> for i in my_gen:
    ...    pass
    Hallo iter 1
    >>> for i in my_gen:
    ...    pass
    Hallo iter 2
    

    如果您想使用旧的迭代器,只需使用 gen().__iter__()

    >>> my_gen = gen().__iter__()
    >>> for i in my_gen:
    ...    pass
    Hallo iter 1
    >>> for i in my_gen:
    ...    pass
    

    【讨论】:

    • 哦哈哈我应该看到的。那么你会如何建议实施呢?
    【解决方案2】:

    正如@napuzba 所指出的,__iter__ 每次使用时都会返回一个全新的生成器。相反,将状态存储在self

    class gen():
        def __init__(self):
            self.count = 0
        def __iter__(self):
            while self.count < 20:
                self.count += 1
                yield self.count
    

    【讨论】:

      猜你喜欢
      • 2014-06-13
      • 2015-02-10
      • 2018-11-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      • 1970-01-01
      • 2010-12-21
      相关资源
      最近更新 更多