除非我疯了,if None not in x
和if not None in x
是等效的。是否有首选版本?我猜None not in
更具英语特色,因此更符合Pythonic,但not None in
更像其他语言的语法。是否有首选版本?
它们编译成相同的字节码,因此它们是等价的。
>>> 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
就没有歧义了。
not (None in x)
(为了明确起见添加括号)是普通的布尔否定。然而,
None not in x
这是一种为了让代码更易读而添加的特殊语法(在in前面使用and、or等无意义且不可行)。如果需要使用这种特殊情况,请使用它。
同样适用于:
foo is not None
对比。
not foo is None
我认为使用“is not”更容易理解。此外,如果该表达式是更大布尔表达式的一部分,则“not”的范围立即变得清晰明了。