python - 简洁的书写方式(a + b == c 或 a + c == b 或 b + c == a)

标签 python boolean

有没有更简洁或者pythonic的方式来编写 boolean 表达式

a + b == c or a + c == b or b + c == a

我想出了

a + b + c in (2*a, 2*b, 2*c)

但这有点奇怪。

最佳答案

如果我们看一下 Python 之禅,请强调我的:

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

最 Pythonic 的解决方案是最清晰、最简单、最容易解释的解决方案:

a + b == c or a + c == b or b + c == a

更好的是,您甚至不需要了解 Python 即可理解此代码!这很容易。这是毫无保留的最佳解决方案。其他任何东西都是智力手淫。

此外,这也可能是性能最好的解决方案,因为它是所有短路提案中唯一的一个。如果a + b == c,只进行一次加法和比较。

关于python - 简洁的书写方式(a + b == c 或 a + c == b 或 b + c == a),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32085675/

相关文章:

sql - 我可以将一堆 boolean 列转换为 PostgreSQL 中的单个位图吗?

java - 在Java中获取随机 boolean 值

ruby-on-rails - 检查模型实例是否在rails的named_scope内

java 枚举上的 boolean 运算符

python - 如何使代理对象表现得像它包装的整数?

python - 如何将网页中嵌入的视频链接名称与视频名称一起提取

python - Numpy 基于时间的矢量操作,其中前面元素的状态很重要 - for 循环是否合适?

python - 将字符串设置为 pandas DataFrame 的索引

python - 基于字符列表的单词组合

ruby - 在 Ruby 中返回 boolean 值的方法或属性的有利命名约定是什么?