gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:44:50 25 4
gpt4 key购买 nike

在这方面找不到太多。试图比较 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com