“没有一个不在”。与“not None in”相比
除非我疯了 if None not in x
和 if 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它们编译为相同的字节码,所以是的,它们是等效的。
文档 还清楚地表明两者是等效的:
正如您提到的
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.
The documentation also makes it clear that the two are equivalent:
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 meantnot (y in x)
or(not y) in x
. There is no ambiguity if you usenot in
.该表达式
(为了清楚起见添加了括号)是一个普通的布尔否定。然而,
是否添加了特殊语法以获得更易读的代码(这里不可能,也没有意义,在 in 前面使用 and、or 等)。如果添加了这个特殊情况,请使用它。
这同样适用于
vs。
我发现“不是”更容易阅读。作为额外的好处,如果表达式是较大布尔表达式的一部分,则 not 的范围会立即清晰。
The expression
(parens added for clarity) is an ordinary boolean negation. However,
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
vs.
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.