How to apply a logical operator to all elements in a python list

后端 未结 6 1668
日久生厌
日久生厌 2021-01-29 22:25

I have a list of booleans in python. I want to AND (or OR or NOT) them and get the result. The following code works but is not very pythonic.

def apply_and(alist         


        
6条回答
  •  礼貌的吻别
    2021-01-29 22:52

    Logical and across all elements in a_list:

    all(a_list)
    

    Logical or across all elements in a_list:

    any(a_list)
    

    If you feel creative, you can also do:

    import operator
    def my_all(a_list):
      return reduce(operator.and_, a_list, True)
    
    def my_any(a_list):
      return reduce(operator.or_, a_list, False)
    

    keep in mind that those aren't evaluated in short circuit, whilst the built-ins are ;-)

    another funny way:

    def my_all_v2(a_list):
      return len(filter(None,a_list)) == len(a_list)
    
    def my_any_v2(a_list):
      return len(filter(None,a_list)) > 0
    

    and yet another:

    def my_all_v3(a_list):
      for i in a_list:
        if not i:
          return False
      return True
    
    def my_any_v3(a_list):
      for i in a_list:
        if i:
          return True
      return False
    

    and we could go on all day, but yes, the pythonic way is to use all and any :-)

    By the way, Python has not tail recursion elimination, so don't try to translate LISP code directly ;-)

提交回复
热议问题