我在尝试比较时注意到了这一点:
if len(sys.argv) >= 2:
pass
但是我已经这样做了并且仍然是正确的(花了我一些时间来找到错误。
if sys.argv >= 2: # This is True!!!
pass
以下是更多示例:
>>> {} > 2
True
>>> [] > 2
True
>>> () > 2
True
>>> set > 2
True
>>> str > 2
True
>>> enumerate > 2
True
>>> __builtins__ > 2
True
>>> class test:
... pass
...
>>> test
<class __main__.test at 0xb751417c>
>>> test > 2
True
在python3.x中,它会导致TypeError。
您正在比较不同的类型。在 Python 2 中,类型按名称相对于彼此排序,数字类型始终先于其他所有内容排序。
引入此功能是为了允许对包含不同类型数据的异构列表进行排序。
Python 3 纠正了这种有点令人惊讶的行为,除非自定义比较钩子特别允许,否则比较类型(数字或彼此之间)总是一个错误:
>>> {} > 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: dict() > int()
>>> class Foo:
... def __gt__(self, other):
... if isinstance(other, int):
... return True
...
>>> Foo() > 3
True