【问题标题】:Difference between (a not in b) & (not a in b). Python [duplicate](a not in b) & (not a in b) 之间的区别。 Python [重复]
【发布时间】:2014-10-28 16:51:12
【问题描述】:

您好,有人能解释一下 Python 中“in”运算符的工作机制吗?

我现在正在处理以下示例:

print ('a' not in ['a', 'b'])  # outputs False
print (not 'a' in ['a', 'b'])  # outputs False   --   how ???

print ('c' not in ['a', 'b'])  # outputs True
print (not 'c' in ['a', 'b'])  # outputs True


print (not 'a')   # outputs False
# ok is so then...
print (not 'a' in ['b', False])   # outputs True --- why ???

我现在想知道为什么会这样。如果有人知道,请分享您的知识。 谢谢=)

【问题讨论】:

  • a not innot a in 相等
  • 请注意,python 样式指南说您应该使用a not in,即使它们的作用相同。
  • 您可以轻松地将其更改为 (not 'a') in ['b', False],这将为您提供您显然期望的答案(因为括号始终表示更高的优先级)
  • peephole optimizernot a in b 等语句转换为a not in b。所以,这是使用 not in 的另一个原因,它在 IMO 上也具有很高的可读性。

标签: python


【解决方案1】:

in has higher precedence than not。因此,执行包含检查,然后在需要时否定结果。 'a' 不在['b', False] 中,结果False 被取反为True

【讨论】:

    【解决方案2】:

    not 关键字基本上“反转”了此处返回的布尔值。

    对于第一个示例,a 在数组中,所以这是真的,但 not true 是假的。太假了。

    对于第二个示例,a 不在数组中,所以这是错误的,但 not false 是正确的。如此真实。

    【讨论】:

      【解决方案3】:

      print (not 'a' in ['a', 'b'])

      这样分解:

      not 'a' 本身的计算结果为 False(因为除了 0、None、False、空列表和空字典之外,任何东西都被视为 True

      false 不在['a','b'] 中,所以 False in ['a','b'] 计算结果为 False

      最后一个not 'a' 计算为False 所以False in ['b', False] 计算为True

      【讨论】:

      • 这个解释是错误的。它没有考虑运算符的优先级。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 2014-12-05
      • 2016-05-04
      • 1970-01-01
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      相关资源
      最近更新 更多