【问题标题】:Python comparing int, float, etc to lists [duplicate]Python将int,float等与列表进行比较[重复]
【发布时间】:2013-09-04 19:00:44
【问题描述】:

所以这一直困扰着我,我无法在网上找到任何关于它的信息。有人可以在python中解释这种行为吗?为什么它返回 True 而不是抛出异常?谢谢

In [1]: 1 < [1, 2, 3]
Out[1]: True

【问题讨论】:

标签: python


【解决方案1】:

它确实抛出异常——无论如何,这些天来:

$ python3
Python 3.3.0 (default, Apr 17 2013, 13:40:43) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 < [1,2,3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() < list()

过去,Python 过去常常让比较像这样通过,因为有时能够在异构容器中自动对所有内容进行排序很方便,但这导致的错误多于其便利性,因此它在 Python 3 中得到了修复.

【讨论】:

  • -1 表示 Python 2 已经过时或稀有。
  • @Marcin:我大部分工作日(实际上包括现在)都在用 Python 2.7 编写代码,所以我不确定我怎么会认为它已经过时,或者为什么我会这么说。然而,它绝对不是 Python 开发的前沿,而且 Python 3 已经有很多年的发展,3.4 正在开发中,所以我认为“过去”是有道理的。无论如何,有other people 使用完全相反的标准投反对票,所以我想这一切最终都会平衡!
【解决方案2】:

这是一种使排序更容易的尝试。 Python 试图使没有有意义的比较操作的对象以一致但任意的顺序进行比较。在 Python 3 中,他们改变了它;这将是 Python 3 中的 TypeError。

【讨论】:

    【解决方案3】:

    如果我没记错的话,您在 py2 中看到的行为实际上是在比较类型。

    >>> 1 < [1,2,3]
    True
    >>> 1 > [1,2,3]
    False
    >>> int < list
    True
    >>> int > list
    False
    

    随着我的深入研究,我认为它比较了类型的名称,尽管可能有些间接,也可能通过其中之一进行比较,尽管我不能说:

    >>> repr(int)
    "<type 'int'>"
    >>> int.__name__
    'int'
    >>> repr(list)
    "<type 'list'>"
    >>> list.__name__
    'list'
    
    >>> 'int' < 'list'
    True
    >>> "<type 'int'>" < "<type 'list'>"
    True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-23
      • 2012-11-27
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 2020-08-28
      • 1970-01-01
      • 2018-09-10
      相关资源
      最近更新 更多