gpt4 book ai didi

python - 'or' 是否用在赋值 pythonic 的右侧?

转载 作者:太空狗 更新时间:2023-10-29 22:26:24 25 4
gpt4 key购买 nike

情况

(注意:以下情况只是示例性的。本题适用于任何可以计算为bool的东西)

如果用户不提供自定义列表,则应使用默认列表:

default_list = ...
custom_list = ...
if custom_list:
list = custom_list
else:
list = default_list

您可以将其缩短为:

default_list = ...
custom_list = ...
list = custom_list if custom_list else default_list

现在,根据 https://docs.python.org/2.7/reference/expressions.html#or ...

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

..., or 不返回 bool 值,而是返回 bool 转换不为假的第一个值。因此,以下是有效代码:

list = custom_list or default_list

这类似于 C# Null Coalescing Operator,除了它应该在 Python 中重新命名为 False Coalescing Operator,它返回第一个 non-false 参数。 p>

问题

最后一个例子似乎更容易阅读,但它是否被认为是 pythonic 的?

pep8(程序)和 pylint 都没有提示。

最佳答案

这是完全有效的,您可以使用它。即使是 documentation of or有一个相同的例子。

Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value.

但是,方法有一个限制。如果您想有目的地允许非真实值,那么不可能这样做。

假设您想允许一个空列表

my_list = [] or default_list

将始终提供 default_list。例如,

print [] or [1, 2, 3]
# [1, 2, 3]

但是有了条件表达式我们可以这样处理

custom_list if isinstance(custom_list, list) else default_list

清理旧文件,引用 BDFL's FAQ ,

4.16. Q. Is there an equivalent of C's "?:" ternary operator?

A. Not directly. In many cases you can mimic a?b:c with a and b or
c
, but there's a flaw: if b is zero (or empty, or None -- anything that tests false) then c will be selected instead. In many cases you can prove by looking at the code that this can't happen (e.g. because b is a constant or has a type that can never be false), but in general this can be a problem.

Steve Majewski (or was it Tim Peters?) suggested the following solution: (a and [b] or [c])[0]. Because [b] is a singleton list it is never false, so the wrong path is never taken; then applying [0] to the whole thing gets the b or c that you really wanted. Ugly, but it gets you there in the rare cases where it is really inconvenient to rewrite your code using 'if'.

关于python - 'or' 是否用在赋值 pythonic 的右侧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23403530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com