问题
Couldn't find much on this. Trying to compare 2 values, but they can't be equal. In my case, they can be (and often are) either greater than or less than.
Should I use:
if a <> b:
dostuff
or
if a != b:
dostuff
This page says they're similar, which implies there's at least something different about them.
回答1:
Quoting from Python language reference,
The comparison operators
<>and!=are alternate spellings of the same operator.!=is the preferred spelling;<>is obsolescent.
So, they both are one and the same, but != is preferred over <>.
I tried disassembling the code in 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)
And got the following
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
Both <> and != are generating the same byte code
6 COMPARE_OP 3 (!=)
So they both are one and the same.
Note:
<> is removed in Python 3.x, as per the Python 3 Language Reference.
Quoting official documentation,
!=can also be written<>, but this is an obsolete usage kept for backwards compatibility only. New code should always use!=.
Conclusion
Since <> is removed in 3.x, and as per the documentation, != is the preferred way, better don't use <> at all.
回答2:
Just stick to !=.
<> is outdated! Please check recent python reference manual.
来源:https://stackoverflow.com/questions/27478998/when-to-use-and-operators