Python filter / max combo - checking for empty iterator

后端 未结 4 1183
有刺的猬
有刺的猬 2021-01-12 08:44

(Using Python 3.1)

I know this question has been asked many times for the general question of testing if iterator is empty; obviously, there\'s no neat solution to t

4条回答
  •  我在风中等你
    2021-01-12 09:19

    def f(lst):
      flt = filter(lambda x : x is not None and x != 0, lst)
      try:
        return min(flt)
      except ValueError:
        return None
    

    min throws ValueError when the sequence is empty. This follows the common "Easier to Ask for Forgiveness" paradigm.

    EDIT: A reduce-based solution without exceptions

    from functools import reduce
    def f(lst):
      flt = filter(lambda x : x is not None and x != 0, lst)
      m = next(flt, None)
      if m is None:
        return None
      return reduce(min, flt, m)
    

提交回复
热议问题