python - "a and a or b"的目的是什么?

标签 python ternary-operator

我在 ipython 中遇到了以下代码:

oname = args and args or '_'

那有什么意义呢?为什么不只使用 args 或 '_'

最佳答案

我猜这是 Python 的古老(2.4 或更早版本)变体的遗留问题,当时该语言尚无法使用三元运算符。根据Python Programming FAQ :

Is there an equivalent of C’s ”?:” ternary operator?

Yes, there is. The syntax is as follows:

[on_true] if [expression] else [on_false]

x, y = 50, 25
small = x if x < y else y

Before this syntax was introduced in Python 2.5, a common idiom was to use logical operators:

[expression] and [on_true] or [on_false]

However, this idiom is unsafe, as it can give wrong results when on_true has a false boolean value. Therefore, it is always better to use the ... if ... else ... form.

有问题的行现在可以写成:

# Option 1
oname = args if args else '_'

# Option 2
oname = args or '_'

两者都会产生相同的结果,因为在这种情况下,选项 1 的 [expression] 部分与 [on_true] 部分相同。在我看来,对于 [expression][on_true] 相同的情况,选项 2 可以被视为选项 1 的缩写形式。您选择使用哪一个是个人喜好。

这可能会给我们一个线索,让我们知道自从有问题的代码被触及以来已经有多久了!

关于python - "a and a or b"的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53209280/

相关文章:

python - 具有两种颜色的 Matplotlib 绘图分布

python - 类型 'set' 的对象不可 JSON 序列化

python - 将 HTMLFill 与 Pyramid 的 @view_config 结合使用

python - 包装 print() 的自定义打印函数

asp.net - 使用三元运算符在Razor中输出包含空格的字符串

swift - "Expression type ' Bool ' is ambiguous without more context"三元运算

python - 如果函数 : if column A==1 AND 1 column B is in list X and column C is not null, 1。否则,0

PHP:是否有空合并运算符的反面?

java - 为什么三元运算符会意外地转换整数?

javascript - 三元语句是否比 javascript 中的 if/then/else 语句更快?