代码之家  ›  专栏  ›  技术社区  ›  Seungho Lee

如何缩短if语句中的“is not None”

  •  -1
  • Seungho Lee  · 技术社区  · 8 年前

    在蟒蛇3中 Truth Value Testing 在PEP8中,这是为了 if A is None: ,可以转换为 if not A: . 像这样,既然下面的代码看起来很混乱,很难一下子理解,那么它能用这样或那样的方式表达得更简洁吗?

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

    2 回复  |  直到 8 年前
        1
  •  2
  •   OLIVER.KOO    8 年前

    any() all() 但你也要检查一下 None 存在于列表中,包括 A , B , C

    if not (None in [A,B,C]): if None not in [A, B, C]: (黑色)


    旁注(深潜)

    if A and B and C: if A is not None 和 if A 做不同的事。

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

    在Python中测试身份。因为在运行的Python脚本/程序中只有一个实例不存在

    看看这个 post 还有这个 post

        2
  •  3
  •   superbeck    8 年前

    any()和all()可以与理解一起使用,在这些情况下也会有所帮助。

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