问题描述
在测试会员资格时,我们可以使用:
x 不在 y
或者:
y 中没有 x
根据x
和y
,这个表达式可以有很多可能的上下文.例如,它可以用于子字符串检查、列表成员资格、字典键存在.
- 这两种形式总是等价的吗?
- 有首选的语法吗?
他们总是给出相同的结果.
事实上,not 'ham' in 'spam and Eggs'
似乎是执行单个not in"操作的特殊情况,而不是执行in"操作然后否定结果:
一开始我以为他们总是给出相同的结果,但是 not
本身只是一个低优先级的逻辑否定运算符,可以应用于 a in b
就像任何其他布尔表达式一样容易,而 not in
是一个单独的运算符,以方便和清晰.
上面的拆解很有启发性!虽然 not
显然是一个逻辑否定运算符,但形式 not a in b
是特殊情况,因此它实际上并没有使用通用运算符.这使得 not a in b
与 a not in b
字面上相同的表达式,而不仅仅是产生相同值的表达式.
When testing for membership, we can use:
x not in y
Or alternatively:
not x in y
There can be many possible contexts for this expression depending on x
and y
. It could be for a substring check, list membership, dict key existence, for example.
- Are the two forms always equivalent?
- Is there a preferred syntax?
They always give the same result.
In fact, not 'ham' in 'spam and eggs'
appears to be special cased to perform a single "not in" operation, rather than an "in" operation and then negating the result:
>>> import dis
>>> def notin():
'ham' not in 'spam and eggs'
>>> dis.dis(notin)
2 0 LOAD_CONST 1 ('ham')
3 LOAD_CONST 2 ('spam and eggs')
6 COMPARE_OP 7 (not in)
9 POP_TOP
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
>>> def not_in():
not 'ham' in 'spam and eggs'
>>> dis.dis(not_in)
2 0 LOAD_CONST 1 ('ham')
3 LOAD_CONST 2 ('spam and eggs')
6 COMPARE_OP 7 (not in)
9 POP_TOP
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
>>> def not__in():
not ('ham' in 'spam and eggs')
>>> dis.dis(not__in)
2 0 LOAD_CONST 1 ('ham')
3 LOAD_CONST 2 ('spam and eggs')
6 COMPARE_OP 7 (not in)
9 POP_TOP
10 LOAD_CONST 0 (None)
13 RETURN_VALUE
>>> def noteq():
not 'ham' == 'spam and eggs'
>>> dis.dis(noteq)
2 0 LOAD_CONST 1 ('ham')
3 LOAD_CONST 2 ('spam and eggs')
6 COMPARE_OP 2 (==)
9 UNARY_NOT
10 POP_TOP
11 LOAD_CONST 0 (None)
14 RETURN_VALUE
I had thought at first that they always gave the same result, but that not
on its own was simply a low precedence logical negation operator, which could be applied to a in b
just as easily as any other boolean expression, whereas not in
was a separate operator for convenience and clarity.
The disassembly above was revealing! It seems that while not
obviously is a logical negation operator, the form not a in b
is special cased so that it's not actually using the general operator. This makes not a in b
literally the same expression as a not in b
, rather than merely an expression that results in the same value.
这篇关于“x 不在 y"中或“y 中没有 x"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!