【问题标题】:How to shorten the "is not None" in the if statement如何缩短 if 语句中的“不是无”
【发布时间】:2018-10-10 17:24:21
【问题描述】:

在 Python3 中,PEP8 中的Truth Value Testing 表示对于if A is None:,它可以转换为if not A:。像这样,既然下面的代码看起来如此凌乱且难以立即掌握,是否可以用一种或另一种方式更简洁地表达它?

if A is not None and B is not None and C is not None:

【问题讨论】:

  • 你的逻辑颠倒了。 if A is None 可以有时if not A 替换,if A is not None 可以有时被替换为if A,这取决于A 的可能值。因此,根据上下文将 if 语句替换为 if A and B and C 可能是合适的。
  • if A:if A is not None: 在语义上等效。我很确定 PEP8 确实没有这么说,因为这不是风格问题。
  • A = 0 -- > if A: 不会进入 if 块。 if A is not None: 将进入 if 块
  • 我编辑了你指出的逻辑!谢谢!

标签: python python-3.x if-statement pep8


【解决方案1】:

any() 和 all() 可以与理解一起使用以帮助解决这些情况。

if all([x is not None for x in [A,B,C]]):

【讨论】:

    【解决方案2】:

    我同意使用 any()all() 的超级贝克,但您还可以检查 None 是否存在于包括 ABC 的列表中

    if not (None in [A,B,C]): 或更直观的if None not in [A, B, C]: (Blckknght)


    旁注(深入了解)

    无论哪种方式,我都不鼓励使用if A and B and C:,因为if A is not Noneif A 做不同的事情。

    if A: 调用A.__nonzero__() 并使用该函数的返回值。

    if A is not None 在 Python 中测试身份。因为在运行的 Python 脚本/程序中只有一个 None 实例

    检查这个post和这个post

    【讨论】:

    • __nonzero__ 名称仅在 Python 2 中。它在 Python 3 中被 __bool__ 取代。
    • 您也可以在您的解决方案中使用if None not in [A, B, C]。 (X not in Ynot X in Y 的替代拼写。)
    猜你喜欢
    • 2022-06-15
    • 2012-04-06
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 2022-11-01
    • 2022-11-23
    相关资源
    最近更新 更多