我想创建一个从两个生成器提取的生成器,但是当条件为false时不消耗两个生成器的输入。
我一直在使用itertools docs作为参考,这很有帮助,但是看来我想做的事在itertools中是不可能的。
这是我想通过的pytest:
def test_itertools_example(self):
import itertools
cond = itertools.cycle([True, False])
none = itertools.repeat(None)
data = itertools.count(1, 1)
every_other = (d if c else n for (c, d, n) in zip(cond, data, none))
assert next(every_other) == 1
assert next(every_other) is None
assert next(every_other) == 2 # this is 3 and i want 2 but 2 got dropped on the previous call
assert next(every_other) is None
您可以写:
every_other = (next(data) if c else next(none) for c in cond)