Python 中的 “not in” 和 “is not” 运算符

在 Python 中,not inis not 这两个运算符经常被用来进行比较和判断。然而,许多用户对这两个运算符是否都是运算符以及它们之间的区别感到困惑。有些人甚至认为 not inis not 仅仅是 not x innot x is 的简写形式。
Python 中的 “not in” 和 “is not” 运算符_第1张图片

2. 解决方法

为了澄清这个疑惑,我们可以通过 Python 的 dis 模块来查看这两个运算符的字节码。dis 模块可以帮助我们查看 Python 代码的字节码表示形式。

>>> dis.dis(compile('not a in b', '', 'exec'))
  1           0 LOAD_NAME                0 (a)
  http://www.jshk.com.cn/mb/reg.asp?kefu=xiaoding;//爬虫IP免费获取;
              3 LOAD_NAME                1 (b)
              6 COMPARE_OP               7 (not in)
              9 POP_TOP
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE
>>> dis.dis(compile('a not in b', '', 'exec'))
  1           0 LOAD_NAME                0 (a)
              3 LOAD_NAME                1 (b)
              6 COMPARE_OP               7 (not in)
              9 POP_TOP
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE

从上面的字节码中可以看出,not a in ba not in b 这两个形式都编译成了相同的字节码,即 COMPARE_OP 操作符,其中 COMPARE_OP 的参数为 7 (not in)。这表明 not in 确实是一个运算符,并且它与 not x in 是等价的。

同样地,我们也可以使用 dis 模块来查看 is not 运算符的字节码。

>>> dis.dis(compile('not a is b', '', 'exec'))
  1           0 LOAD_NAME                0 (a)
              3 LOAD_NAME                1 (b)
              6 COMPARE_OP               9 (is not)
              9 POP_TOP
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE
>>> dis.dis(compile('a is not b', '', 'exec'))
  1           0 LOAD_NAME                0 (a)
              3 LOAD_NAME                1 (b)
              6 COMPARE_OP               9 (is not)
              9 POP_TOP
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE

从上面的字节码中可以看出,not a is ba is not b 这两个形式也编译成了相同的字节码,即 COMPARE_OP 操作符,其中 COMPARE_OP 的参数为 9 (is not)。这表明 is not 也是一个运算符,并且它与 not x is 是等价的。

因此,我们可以得出结论,not inis not 这两个运算符都是 Python 中的运算符,并且它们与 not x innot x is 是等价的。

代码例子

我们来看看一些代码示例来更好地理解这两个运算符的用法:

# 使用 not in 运算符来判断一个元素是否不在一个列表中
if 'a' not in ['b', 'c', 'd']:

    print('a is not in the list.')

# 使用 is not 运算符来判断两个变量是否不指向同一个对象
if x is not y:
    print('x and y are not the same object.')

总结

not inis not 这两个运算符是 Python 中非常有用的运算符,它们可以帮助我们进行各种各样的比较和判断。通过本文,我们已经对这两个运算符有了更深入的了解。

你可能感兴趣的:(python,开发语言)