0

I want to create a generator which pulls from two generators but doesn't consume the input of both when the condition is false.

I have been using the itertools docs as reference which is quite helpful, but it seems what I want to do is not possible within itertools.

here is a pytest I want to pass:

    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
user2240431
  • 338
  • 2
  • 12
  • Maybe this helps? [How to look ahead one element (peek) in a Python generator?](https://stackoverflow.com/questions/2425270/how-to-look-ahead-one-element-peek-in-a-python-generator) – NewPythonUser May 29 '20 at 12:20

1 Answers1

2

You can just write:

every_other = (next(data) if c else next(none) for c in cond)
One Lyner
  • 1,964
  • 1
  • 6
  • 8