原文链接点击这里,本文主要是做收藏。
如果我们在代码中需要检查多个条件语句,此时我们可以使用 all()
或any()
函数来实现我们的目标。一般来说, 当我们有多个 and 条件时使用 all()
,当我们有多个 or 条件时使用 any()
。这种用法将使我们的代码更加清晰易读,可以方便我们在调试时不会遇到麻烦。
all()
的一般例子如下:size = "lg"
color = "blue"
price = 50
# bad practice
if size == "lg" and color == "blue" and price < 100:
print("Yes, I want to but the product.")
更好的处理方法如下:
# good practice
conditions = [
size == "lg",
color == "blue",
price < 100,
]
if all(conditions):
print("Yes, I want to but the product.")
any()
的一般例子如下:# bad practice
size = "lg"
color = "blue"
price = 50
if size == "lg" or color == "blue" or price < 100:
print("Yes, I want to but the product.")
更好的处理方法如下:
# good practice
conditions = [
size == "lg",
color == "blue",
price < 100,
]
if any(conditions):
print("Yes, I want to but the product.")