python - 什么时候使用 `<>` 和 `!=` 运算符?

标签 python python-2.7 python-3.x comparison-operators python-internals

在这方面找不到太多。试图比较 2 个值,但它们不能相等。在我的例子中,它们可以(并且经常)大于或小于。

我应该使用:

if a <> b:
   dostuff

if a != b:
   dostuff

This page说它们相似,这意味着它们至少有一些不同之处。

最佳答案

引自Python language reference ,

The comparison operators <> and != are alternate spellings of the same operator. != is the preferred spelling; <> is obsolescent.

所以,它们是一回事,但是 !=优先于 <> .

我尝试反汇编 Python 2.7.8 中的代码

from dis import dis
form_1 = compile("'Python' <> 'Python'", "string", 'exec')
form_2 = compile("'Python' != 'Python'", "string", 'exec')
dis(form_1)
dis(form_2)

得到以下内容

  1           0 LOAD_CONST               0 ('Python')
              3 LOAD_CONST               0 ('Python')
              6 COMPARE_OP               3 (!=)
              9 POP_TOP
             10 LOAD_CONST               1 (None)
             13 RETURN_VALUE

  1           0 LOAD_CONST               0 ('Python')
              3 LOAD_CONST               0 ('Python')
              6 COMPARE_OP               3 (!=)
              9 POP_TOP
             10 LOAD_CONST               1 (None)
             13 RETURN_VALUE

两者都是 <>!=正在生成相同的字节码

              6 COMPARE_OP               3 (!=)

所以它们是一体的。

注意事项:

<>根据 the Python 3 Language Reference 在 Python 3.x 中被删除.

引用 official documentation ,

!= can also be written <>, but this is an obsolete usage kept for backwards compatibility only. New code should always use !=.

结论

<>在 3.x 中被删除,并且根据文档,!=是首选方式,最好不要使用 <>完全没有。

关于python - 什么时候使用 `<>` 和 `!=` 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27478998/

相关文章:

python - 将行分配给其他行

python - 匹配不完全限定路径

python - 如何在python中实现这个算法?

python - 如何在python中添加编码askopenfile

python - 将 HTML 表数据解析为 JSON 并保存到 Python 2.7 中的文本文件

python - 比较二维 numpy 数组的元素

python-3.x - 在OpenCV中播放电影

python - Lexer 在 Python 中输出 "TypeError: write() argument must be str, not bytes"。我究竟做错了什么?

python - Python timeit : Counter() vs defaultdict() vs dict() 的惊人结果

python - 在 iPython 中使用神圣模块