📜  Python|布尔列表 AND 和 OR 运算

📅  最后修改于: 2022-05-13 01:55:46.099000             🧑  作者: Mango

Python|布尔列表 AND 和 OR 运算

有时,在使用Python列表时,我们可能会遇到一个问题,即我们有一个布尔列表,我们需要找到其中所有元素的布尔 AND 或 OR。这类问题在数据科学领域有应用。让我们讨论解决这两个任务的简单方法。

方法 #1:AND 操作 – 使用all()
此问题的解决方案非常简单,但需要应用程序意识。 all() 执行列表的布尔 AND 并返回结果。

# Python3 code to demonstrate working of
# Boolean List AND and OR operations
# AND Operation - Using all()
  
# initialize list
test_list = [True, True, False, True, False]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Boolean List AND and OR operations
# AND Operation - Using all()
res = all(test_list)
  
# printing result
print("Result after performing AND among elements : " + str(res))
输出 :
The original list is : [True, True, False, True, False]
Result after performing AND among elements : False

方法 #2 : OR 操作 – 使用any()
可以使用any()执行此任务。这将检查列表中的任何 True 元素并在这种情况下返回 True,否则返回 False。

# Python3 code to demonstrate working of
# Boolean List AND and OR operations
# OR operation - Using any()
  
# initialize list
test_list = [True, True, False, True, False]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Boolean List AND and OR operations
# OR operation - Using any()
res = any(test_list)
  
# printing result
print("Result after performing OR among elements : " + str(res))
输出 :
The original list is : [True, True, False, True, False]
Result after performing OR among elements : True