python - 如果条件不那么困惑

标签 python python-3.x

我是 Python 的新手,我想知道是否有更优雅的方式来表达以下 if 条件:

a=0
b=0
c=0
d=0
e=0
f=0

if a!=0 and c!=0 and b==0 and d==0 and e==0 and f==0:
    print("Hello World!")

这是一个简单的玩具示例,但实际上我有超过 6 个字母,事情变得非常困惑。

最佳答案

您的情况基本上分为两部分:

  • 一些变量集全为零
  • 一些变量集都是非零的

然后列出两个列表:

should_be_zero = [b, d, e, f]
should_be_nonzero = [a, c]

然后您可以将您的条件重新表达为:

all(i == 0 for i in should_be_zero) and all(i != 0 for i in should_be_nonzero)

如评论中所述,由于我们讨论的是零/非零整数,因此以上内容等同于

not any(should_be_zero) and all(should_be_nonzero)

关于python - 如果条件不那么困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49086873/

相关文章:

python - SQLite 不在使用之间保存数据

python - 打印功能错误 "End of statement expected"

node.js - NodeJS 和 Python 之间的 RSA 签名不匹配

Python "Multi-Level Decorator"- 这是如何工作的?

python - 使用 pip 安装 Spacy 期间出错

python - '无法在另一个循环运行时运行事件循环')RuntimeError websockets?

python-3.x - PySide/PyQt : Is it possible to make strings that you attach to the QTextBrowser separate clickable units

python - sys.argv[1][-4 :] script meaning

python - openpyxl xlsx 文件单元格值 = 无

java - Python 和 Java 中正则表达式语法的差异