我们可以创建一个条件zip,当为false时不使用输入吗?

问题描述 投票:0回答:1

我想创建一个从两个生成器提取的生成器,但是当条件为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
python generator
1个回答
1
投票

您可以写:

every_other = (next(data) if c else next(none) for c in cond)
© www.soinside.com 2019 - 2024. All rights reserved.