Python filter / max combo - checking for empty iterator

后端 未结 4 1171
有刺的猬
有刺的猬 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:31

    def f(lst):
        # if you want the exact same filtering as the original, you could use
        # lst = [item for item in lst if (item is not None and item != 0)]
    
        lst = [item for item in lst if item]
        if lst: return min(lst)
        else: return None
    

    the list comprehension only allows items that don't evaluate to boolean false (which filters out 0 and None)

    an empty list i.e. [] will evaluate to False, so "if lst:" will only trigger if the list has items

提交回复
热议问题