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

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

    This isn't really cleaner, but it shows a way to package it in a function losslessly:

    def has_elements(iter):
      from itertools import tee
      iter, any_check = tee(iter)
      try:
        any_check.next()
        return True, iter
      except StopIteration:
        return False, iter
    
    has_el, iter = has_elements(iter)
    if has_el:
      # not empty
    

    This isn't really pythonic, and for particular cases, there are probably better (but less general) solutions, like the next default.

    first = next(iter, None)
    if first:
      # Do something
    

    This isn't general because None can be a valid element in many iterables.

    0 讨论(0)
  • 2020-12-05 02:23

    What about:

    In [1]: i=iter([])
    
    In [2]: bool(next(i,False))
    Out[2]: False
    
    In [3]: i=iter([1])
    
    In [4]: bool(next(i,False))
    Out[4]: True
    
    0 讨论(0)
  • 2020-12-05 02:24

    __length_hint__ estimates the length of list(it) - it's private method, though:

    x = iter( (1, 2, 3) )
    help(x.__length_hint__)
          1 Help on built-in function __length_hint__:
          2 
          3 __length_hint__(...)
          4     Private method returning an estimate of len(list(it)).
    
    0 讨论(0)
提交回复
热议问题