在尝试进行比较时,我注意到了这一点:

if len(sys.argv) >= 2:
    pass


但我已经做到了,但仍然是True(花了我一些时间来查找错误。):

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

关于python - 为什么{} | [] |()| str | set |等> n在python2.x中等于True吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19743622/

10-12 16:51
查看更多