if语句中同时判断多个条件的多种方法

时间:2024-03-21 08:34:02

总结一下自己经常用到的python中的if语句同时判断多个条件的不同方法,假设有:

x, y, z = 0, 1, 0
  • 方法一,多个逻辑运算符一起使用,这也是最常用的写法:
if x == 1 or y == 1 or z == 1:
print('passed') if x or y or z:
print('passed'
  • 方法二,使用成员操作符in,比较Pythonic的一种用法:
if 1 in (x, y, z):
print('passed')
  • 方法三,使用any或则all函数:
if any((x, y, z)):
print('passed') if all((x, y, z)):
print('passed')