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

后端 未结 6 1672
日久生厌
日久生厌 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 23:08

    The idiom for such operations is to use the reduce function (global in Python 2.X, in module functools in Python 3.X) with an appropriate binary operator either taken from the operator module or coded explicitly. In your case, it's operator.and_

    reduce(operator.and_, [True, True, False])
    

提交回复
热议问题