“x不在"与“不是 x in" [英] "x not in" vs. "not x in"
问题描述
我注意到这两者的工作方式相同:
if x not in list
and if not x in list
.
在某些情况下,两者之间是否存在某种差异?两者兼而有之,还是只是因为有些人写一个或另一个更自然?
我更有可能在其他人的代码中看到哪个?
这两种形式产生了相同的字节码,你可以清楚地验证:
<预><代码>>>>导入文件>>>dis.dis(compile('if x not in d: pass', '', 'exec'))1 0 LOAD_NAME 0 (x)3 LOAD_NAME 1 (d)6 COMPARE_OP 7(不在)9 JUMP_IF_FALSE 4(到 16)12 POP_TOP13 JUMP_FORWARD 1(到 17)>>16 POP_TOP>>17 LOAD_CONST 0 (无)20 RETURN_VALUE>>>dis.dis(compile('if not x in d: pass', '', 'exec'))1 0 LOAD_NAME 0 (x)3 LOAD_NAME 1 (d)6 COMPARE_OP 7(不在)9 JUMP_IF_FALSE 4(到 16)12 POP_TOP13 JUMP_FORWARD 1(到 17)>>16 POP_TOP>>17 LOAD_CONST 0 (无)20 RETURN_VALUE很明显它们在语义上是相同的.
就风格而言,PEP 8 没有提到这个问题.
就我个人而言,我非常喜欢 if x not in y
形式——这立即表明 not in
是一个单一的操作符,and强>读起来像英语".if not x in y
可能会误导一些读者认为它的意思是if (not x) in y
,读起来不像英语,完全没有补偿优势.
I've noticed that both of these work the same:
if x not in list
and if not x in list
.
Is there some sort of difference between the two in certain cases? Is there a reason for having both, or is it just because it's more natural for some people to write one or the other?
Which one am I more likely to see in other people's code?
The two forms make identical bytecode, as you can clearly verify:
>>> import dis
>>> dis.dis(compile('if x not in d: pass', '', 'exec'))
1 0 LOAD_NAME 0 (x)
3 LOAD_NAME 1 (d)
6 COMPARE_OP 7 (not in)
9 JUMP_IF_FALSE 4 (to 16)
12 POP_TOP
13 JUMP_FORWARD 1 (to 17)
>> 16 POP_TOP
>> 17 LOAD_CONST 0 (None)
20 RETURN_VALUE
>>> dis.dis(compile('if not x in d: pass', '', 'exec'))
1 0 LOAD_NAME 0 (x)
3 LOAD_NAME 1 (d)
6 COMPARE_OP 7 (not in)
9 JUMP_IF_FALSE 4 (to 16)
12 POP_TOP
13 JUMP_FORWARD 1 (to 17)
>> 16 POP_TOP
>> 17 LOAD_CONST 0 (None)
20 RETURN_VALUE
so obviously they're semantically identical.
As a matter of style, PEP 8 does not mention the issue.
Personally, I strongly prefer the if x not in y
form -- that makes it immediately clear that not in
is a single operator, and "reads like English". if not x in y
may mislead some readers into thinking it means if (not x) in y
, reads a bit less like English, and has absolutely no compensating advantages.
这篇关于“x不在"与“不是 x in"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!