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

后端 未结 9 1851
野的像风
野的像风 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:00

    In Python 2.6+, if name sentinel is bound to a value which the iterator can't possibly yield,

    if next(iterator, sentinel) is sentinel:
        print('iterator was empty')
    

    If you have no idea of what the iterator might possibly yield, make your own sentinel (e.g. at the top of your module) with

    sentinel = object()
    

    Otherwise, you could use, in the sentinel role, any value which you "know" (based on application considerations) that the iterator can't possibly yield.

提交回复
热议问题