Python如何部分消耗可迭代生成器(没有 `next` )?

标签 python iterator generator

我有一个充当可迭代生成器的类(根据 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"?

最佳答案

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

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

关于Python如何部分消耗可迭代生成器(没有 `next` )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64837827/

相关文章:

python - 使用 Ajax 按钮过滤 Django 模型

iterator - 如何在迭代向量时改变向量中的另一个项目,而不是向量本身?

c++ - 构造函数中的 noob Iterator 运行时错误

python - 如何生成随机数,同时避免已使用的数字

Python 生成器函数名称——前缀有用吗?

python - Ruby 与 Python : which one is easier to keep track of different language versions?

python - 在自定义函数上加入两个 RDD - SPARK

python - 反转 `pairwise` 生成器

Python 列表 : Appending a string and removing ALL quotations

java - 拥有某种惰性迭代器的最佳方法是什么,其中仅根据请求评估返回值?