Python:避免if条件?

发布于 2024-08-24 16:30:13 字数 254 浏览 2 评论 0原文

哪个更好?

if not var:
    var = get_var()
(or)

var = var 或 get_var()

另外,我如何知道两者中哪个更好?
编辑:
史蒂夫的另一个选择,

var = var if var else get_var()

Which is better?

if not var:
    var = get_var()


(or)

var = var or get_var()

Also, How do I know the better of the two?
edit:
One more option from steve,

var = var if var else get_var()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

千と千尋 2024-08-31 16:30:14

两者都没有错。

对于阅读代码的人来说,前者更容易理解。

问问自己,当您思考要解决的问题时,脑海中浮现的概念是否更接近“如果这样,则那样”或“两个几乎但不完全是布尔变量的逻辑或”。

Neither is wrong.

The former is clearer to understand for someone reading the code.

Ask yourself if, when you are thinking about the problem you are trying to solve, the concepts that come to mind are closer to "if this, then that" or "a logical OR of two almost, but not quite, Boolean variables."

假设 or 是一个短路运算符(如果左手为真,则不会评估右手参数),两者最终都会编译为相同的代码。

我更喜欢第一个,因为它更清楚地表达了您的意图。第二个可能更紧凑。

Both will eventually compile to the same code, given that or is a short-circuit operator (it doesn't evaluate the right hand argument if left hand is true).

I'd prefer the first one as it expresses your intent more clearly. The second one is probably more compact.

垂暮老矣 2024-08-31 16:30:14

解释器可能会以两种方式执行它们。在代码可读性方面存在权衡。哪一个语句更容易识别它的作用?当然,第一个更清楚。对我来说,读完这篇文章后,我不得不更多地考虑第二个问题。由于可读性增加,我会使用第一个语句,即使第二个语句稍微“性感”。

希望这有帮助。

-tjw

The interpreter will likely execute them both the way. There are tradeoffs regarding code readability. Which statement is easier to recognize what it does? Certainly, the first is much clearer. For me, reading this post, I had to think more about the second one. I would use the first due to increased readability, even if the second statement is slightly 'sexier'.

Hope this helps.

-tjw

南城追梦 2024-08-31 16:30:13

最好的就是你更喜欢的。我会使用带有 if 的第一个版本,但这非常个人化。

The better is the one you like better. I would use first version with if but this is very personal.

离鸿 2024-08-31 16:30:13

当两种风格变体在风格上如此接近时,我使用 timeit 作为决定因素:更快必然意味着更接近 Python 的主流,即更好。嘿,这比无休止的争论要好,是吗?-) 所以:

$ python -mtimeit -s'var=0; getvar=lambda:0' 'var = var or getvar()'
1000000 loops, best of 3: 0.359 usec per loop
$ python -mtimeit -s'var=0; getvar=lambda:0' 'if not var: var = getvar()'
1000000 loops, best of 3: 0.361 usec per loop
$ python -mtimeit -s'var=1; getvar=lambda:1' 'var = var or getvar()'
10000000 loops, best of 3: 0.123 usec per loop
$ python -mtimeit -s'var=1; getvar=lambda:1' 'if not var: var = getvar()'
10000000 loops, best of 3: 0.0899 usec per loop

if 有它——当 var 为 false 时等效,当 true 时更快>。

When two style variations are so close stylistically, I use timeit as the tie-breaker: faster must mean closer to Python's mainstream, i.e., better. Hey, it's better than endless debate, y?-) So:

$ python -mtimeit -s'var=0; getvar=lambda:0' 'var = var or getvar()'
1000000 loops, best of 3: 0.359 usec per loop
$ python -mtimeit -s'var=0; getvar=lambda:0' 'if not var: var = getvar()'
1000000 loops, best of 3: 0.361 usec per loop
$ python -mtimeit -s'var=1; getvar=lambda:1' 'var = var or getvar()'
10000000 loops, best of 3: 0.123 usec per loop
$ python -mtimeit -s'var=1; getvar=lambda:1' 'if not var: var = getvar()'
10000000 loops, best of 3: 0.0899 usec per loop

the if has it -- equivalent when var is false, faster when it's true.

淡墨 2024-08-31 16:30:13

实际上,如果您试图确定之前是否已使用 get_var 调用来设置 var,那么我认为两种形式都是错误的。 Python 将许多完全普通的值视为布尔值“false”:0、None、[]、(,)、set() 和 {}。因此,假设 var 将是一个整数,而 get_var() 恰好返回 0。现在,无论您使用哪种形式,get_var() 都会被一次又一次地调用,即使我们已经知道 var 是 0!

有几种方法可以检测变量是否已定义:

  • 查看由globals()或locals()返回的字典

  • 将语句 var = var 包装在 try/ except 块中,捕获 NameError

  • 使用像 None 这样的哨兵值,并将 var 初始化为该值;那么你可以测试 if var is None: var = get_var() (使用“is”,而不是“==”)。如果您不幸,并且 None 是从 get_var() 返回的潜在值,那么您需要使用 NOT_DEFINED = object(),用它初始化 var,然后可以测试 if var is NOT_DEFINED

Actually, if you are trying to determine if var has been previously set using a call to get_var, then I would contend that both forms are wrong. Python treats a number of perfectly ordinary values as evaluating to a boolean 'false': 0, None, [], (,), set(), and {}. So let's say var is going to be an integer, and get_var() happens to return 0. Now, regardless of which form you use, get_var() will get called again and again, even though we already know that var is 0!

There are several methods for detecting whether a variable has been defined or not:

  • look in the dict returned by globals() or locals()

  • wrap the statement var = var in a try/except block, trapping on NameError

  • use a sentinel value like None, and initialize var to this value; then you can test for if var is None: var = get_var() (using 'is', not '=='). If you are unlucky, and None is a potential value to be returned from get_var(), then you'll need to define your own special not-yet-defined value, using something like NOT_DEFINED = object(), initialize var with it, and then you can test for if var is NOT_DEFINED.

迷途知返 2024-08-31 16:30:13

对我来说,第一个习惯用法,即使用显式 if 的习惯用法,更可取,因为更明确。

然而,我已经看到 or 构造被引用为首选/更Pythonic 的构造。

因此,一方面,显式优于隐式(Zen 引用),另一方面,短表达式可以被视为 pythonic(尽管较短并不在所有情况下都等同于 pythonic! )

一个密切相关的问题是 最惯用的转换方式None 到空字符串,并且 if 和 the 或 习语都列在那里。

To me, the first idiom, the one using the explicit if, is preferable because more explicit.

However I've seen the or construct being referenced as the preferred / more pythonic one.

So, on the one hand, Explicit is better than implicit (Zen citation), on the other hand, the short expression can be viewed as pythonic (although shorter isn't equivalent to pythonic in all cases!)

A closely related SO question is most idiomatic way to convert None to empty string, and both the if and the or idioms were listed there.

∝单色的世界 2024-08-31 16:30:13

第一个版本对我来说更直观。但话又说回来,这完全取决于你自己的品味。

the first version is more intuitive to me. But then again, its all about your own taste.

扛起拖把扫天下 2024-08-31 16:30:13

第二个更Pythonic,我通常使用它。

Second one is more pythonic, and I normally use that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文