繁体   English   中英

“x 不在 y”或“不在 y 中”

[英]"x not in y" or "not x in y"

在测试成员资格时,我们可以使用:

x not in y

或者:

not x in y

根据xy ,此表达式可以有许多可能的上下文。 例如,它可能用于子字符串检查、列表成员资格、字典键存在。

  • 这两种形式总是等价的吗?
  • 有首选的语法吗?

他们总是给出相同的结果。

事实上, not 'ham' in 'spam and eggs'似乎是执行单个“not in”操作的特殊情况,而不是执行“in”操作然后否定结果:

>>> 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      

我起初还以为他们总是给了相同的结果,但not对自己只是一个低优先级逻辑否定运算符,它可以适用于a in b一样容易,任何其他布尔表达式,而not in为一个为方便和清晰起见,单独的运算符。

上面的拆解一目了然! 似乎虽然not显然是逻辑否定运算符,但形式not a in b是特殊情况,因此它实际上并未使用通用运算符。 这使得not a in ba not in b表达式a not in b完全相同,而不仅仅是产生相同值的表达式。

  1. 不,没有区别。

    操作员not in被定义为具有逆真正价值in

    Python 文档

  2. 我认为not in是首选,因为它更明显,并且他们为它添加了一个特例。

它们的含义相同,但pycodestyle Python 样式指南检查器(以前称为 pep8)更喜欢 规则 E713 中not in运算符:

E713: 成员资格测试不应not in

另请参阅“Python if x is not None or if not x is None ?” 对于非常相似的风格选择。

其他人已经非常清楚地表明,这两个声明在相当低的水平上是等效的。

但是,我认为还没有任何人强调过,既然这让你做出选择,你应该

选择使您的代码尽可能可读的形式。

并且不一定对任何人都尽可能可读,即使这当然是一件好事。 不,请确保代码对您来说尽可能具有可读性,因为您是最有可能稍后回到此代码并尝试阅读它的人。

在 Python 中,没有区别。 并且没有偏好。

从语法上讲,它们是相同的语句。 我会很快声明, 'ham' not in 'spam and eggs'中的'ham' not in 'spam and eggs'传达了更清晰的意图,但我已经看到代码和场景中, not 'ham' in 'spam and eggs'比另一个传达了更清晰的含义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM