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

后端 未结 6 1671
日久生厌
日久生厌 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:43

    As the other answers show, there are multiple ways to accomplish this task. Here's another solution that uses functions from the standard library:

    from functools import partial
    
    apply_and = all
    apply_or = any
    apply_not = partial(map, lambda x: not x)
    
    if __name__ == "__main__":
        ls = [True, True, False, True, False, True]
        print "Original: ", ls
        print "and: ", apply_and(ls)
        print "or: ", apply_or(ls)
        print "not: ", apply_not(ls)
    

提交回复
热议问题