“没有一个不在”。与“not None in”相比

发布于 2024-09-16 13:40:07 字数 174 浏览 4 评论 0原文

除非我疯了 if None not in xif not None in x 是等价的。有首选版本吗?我猜 None not in 更英语,因此更Pythonic,但 not None in 更像其他语言语法。有首选版本吗?

Unless I'm crazy if None not in x and if not None in x are equivalent. Is there a preferred version? I guess None not in is more english-y and therefore more pythonic, but not None in is more like other language syntax. Is there a preferred version?

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

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

发布评论

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

评论(2

悲歌长辞 2024-09-23 13:40:08

它们编译为相同的字节码,所以是的,它们是等效的。

>>> import dis
>>> dis.dis(lambda: None not in x)
  1           0 LOAD_CONST               0 (None)
              3 LOAD_GLOBAL              1 (x)
              6 COMPARE_OP               7 (not in)
              9 RETURN_VALUE
>>> dis.dis(lambda: not None in x)
  1           0 LOAD_CONST               0 (None)
              3 LOAD_GLOBAL              1 (x)
              6 COMPARE_OP               7 (not in)
              9 RETURN_VALUE

文档 还清楚地表明两者是等效的:

x not in s 返回 x in s 的否定。

正如您提到的 None not in x 是更自然的英语,所以我更喜欢使用它。

如果您编写not y in x,则可能不清楚您的意思是not (y in x)还是(not y) in x。如果使用 not in 就不会产生歧义。

They compile to the same bytecode, so yes they are equivalent.

>>> import dis
>>> dis.dis(lambda: None not in x)
  1           0 LOAD_CONST               0 (None)
              3 LOAD_GLOBAL              1 (x)
              6 COMPARE_OP               7 (not in)
              9 RETURN_VALUE
>>> dis.dis(lambda: not None in x)
  1           0 LOAD_CONST               0 (None)
              3 LOAD_GLOBAL              1 (x)
              6 COMPARE_OP               7 (not in)
              9 RETURN_VALUE

The documentation also makes it clear that the two are equivalent:

x not in s returns the negation of x in s.

As you mention None not in x is more natural English so I prefer to use this.

If you write not y in x it might be unclear whether you meant not (y in x) or (not y) in x. There is no ambiguity if you use not in.

落在眉间の轻吻 2024-09-23 13:40:08

该表达式

not (None in x) 

(为了清楚起见添加了括号)是一个普通的布尔否定。然而,

None not in x

是否添加了特殊语法以获得更易读的代码(这里不可能,也没有意义,在 in 前面使用 and、or 等)。如果添加了这个特殊情况,请使用它。

这同样适用于

foo is not None

vs。

not foo is None

我发现“不是”更容易阅读。作为额外的好处,如果表达式是较大布尔表达式的一部分,则 not 的范围会立即清晰。

The expression

not (None in x) 

(parens added for clarity) is an ordinary boolean negation. However,

None not in x

is special syntax added for more readable code (there's no possibility here, nor does it make sense, to use and, or, etc in front of the in). If this special case was added, use it.

Same applies to

foo is not None

vs.

not foo is None

I find the "is not" much clearer to read. As an additional bonus, if the expression is part of a larger boolean expression, the scope of the not is immediately clear.

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