“a and a or b”的目的是什么?

9

我在IPython中发现了以下代码:

oname = args and args or '_'

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

3
这可以被重写为args or '_' - Willem Van Onsem
@Igle 我知道 a if b else ca or b,我只是想知道我看到的是否有逻辑... - elyashiv
1
请向下滚动,到 https://dev59.com/IXRC5IYBdhLWcg3wJNqf#394887 查看翻译后的文本。 - Tim
1
如果 args 是“真实的”,则 onameargs,否则为 '_' - Willem Van Onsem
@TimCastelijns 那么,这只是为了防止我们想要的不是args,如果args为真? - elyashiv
1个回答

9

我猜这是 Python 古老版本(2.4 或更早)的一个遗留问题,当时该语言还没有三目运算符。根据 Python 编程 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的缩写形式。选择哪一种方式是个人喜好。
这可能会给我们一个线索,表明涉及的代码已经有多长时间没有被碰过了!

好的信息,谢谢! - Rocky Li
1
我不确定我同意这是一个重复的问题。问题不在于三元运算符是否存在,而在于为什么在这种情况下使用[value] and [value] or [alternate_value]语法。 - Jonah Bishop
1
为什么不使用 oname = args or '_' - L3viathan
@tobias_k 我指的是“现在应该写成”。 - L3viathan
1
我已经更新了我的答案,包括两种可能性,因为两者都是有效的并产生相同的结果。我更喜欢前者,因为它使用内置的三元运算符,并使代码与之前的想法保持一致。 - Jonah Bishop
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接