One-liner to check whether an iterator yields at least one element?

后端 未结 9 1856
野的像风
野的像风 2020-12-05 01:45

Currently I\'m doing this:

try:
    something = iterator.next()
    # ...
except StopIteration:
    # ...

But I would like an expression th

9条回答
  •  甜味超标
    2020-12-05 02:05

    The best way to do that is with a peekable from more_itertools.

    from more_itertools import peekable
    iterator = peekable(iterator)
    if iterator:
        # Iterator is non-empty.
    else:
        # Iterator is empty.
    

    Just beware if you kept refs to the old iterator, that iterator will get advanced. You have to use the new peekable iterator from then on. Really, though, peekable expects to be the only bit of code modifying that old iterator, so you shouldn't be keeping refs to the old iterator lying around anyway.

提交回复
热议问题