【问题标题】:Evaluating result of expression in if-statement in python [duplicate]评估python中if语句中的表达式结果[重复]
【发布时间】:2011-07-22 10:18:44
【问题描述】:

可能重复:
How to assign a variable in IF, and then return it. (Python)

在 Python 中有没有更好的方法来做到这一点?:

myVal = getVal()

if not myVal:
    continue

我想做这样的事情:

if not (myVal = getVal()):
    continue

但这不是有效的语法。有没有其他方法可以像在 PHP 和 Perl 中那样在一行上做到这一点?

【问题讨论】:

  • Python 高度重视代码的清晰度。你不应该这样做。

标签: python syntax


【解决方案1】:

具有赋值的返回值不是pythonic。在 python 中,赋值意味着将对象绑定到一个名称,而不是将值放在内存位置。

【讨论】:

    【解决方案2】:

    不,你不能这样做。

    我会说这是因为它太容易与if not (myVal == getVal()): 混淆。

    【讨论】:

      【解决方案3】:

      不,你不能这样做。

      然而,几乎所有这样的情况都可以在 python 中更干净地完成。但是,为了向您展示如何做到这一点,我们需要更多的上下文。特别是,你正在继续的这个循环是如何构造的。

      【讨论】:

        【解决方案4】:

        你可以试试这个,(取决于 getVal 可以返回什么):

        if not getVal():
            continue
        

        【讨论】:

          猜你喜欢
          • 2019-02-06
          • 2016-11-11
          • 1970-01-01
          • 1970-01-01
          • 2020-07-08
          • 2013-01-10
          • 1970-01-01
          • 1970-01-01
          • 2014-12-08
          相关资源
          最近更新 更多