为什么在python 2.x中int(50)< str(5)? [英] Why is int(50)<str(5) in python 2.x?
问题描述
在python 3中, int(50)<'2'
导致 TypeError
,它应该是。但是,在python 2.x中, int(50)<'2'
返回 True
(这也是其他数字格式的情况,但py2和py3中都存在 int
。那么,我的问题有几个部分:
In python 3, int(50)<'2'
causes a TypeError
, and well it should. In python 2.x, however, int(50)<'2'
returns True
(this is also the case for other number formats, but int
exists in both py2 and py3). My question, then, has several parts:
- 为什么Python 2.x(< 3?)允许这种行为?
- (谁认为允许这个开头是个好主意?)
- 是指
ord
/chr
? - 是否有一些不太明显的二进制格式?
- Is it referring to
ord
/chr
? - Is there some binary format which is less obvious?
推荐答案
它就像这样 1 。
>>> float() == long() == int() < dict() < list() < str() < tuple()
True
数字比较小于容器。数字类型将转换为通用类型,并根据其数值进行比较。容器按其名称的字母值进行比较。 2
Numbers compare as less than containers. Numeric types are converted to a common type and compared based on their numeric value. Containers are compared by the alphabetic value of their names.2
来自 docs :
CPython实现细节:不同的对象除数字以外的类型按其类型名称排序;不支持正确比较的相同类型的对象按其地址排序。
CPython implementation detail: Objects of different types except numbers are ordered by >their type names; objects of the same types that don’t support proper comparison are >ordered by their address.
不同内置类型的对象按字母顺序按类型名称进行比较。 int
以'i'开头, str
以<$ c $开头c> s 所以 int
小于任何 str
。
Objects of different builtin types compare alphabetically by the name of their type .int
starts with an 'i' and str
starts with an s
so any int
is less than any str
.
- 我不知道。
- 醉酒大师。
- 这是指任意订单。
- 否。
回应关于 long<的评论int
>>> int < long
True
您可能意味着这些类型的值,在这种情况下数字比较适用。
You probably meant values of those types though, in which case the numeric comparison applies.
1这一切都在Python 2.6.5上
2感谢kRON为我解决这个问题。我以前从未想过将数字与 dict
进行比较,数字的比较就是那些很容易被忽视的事情之一。
2 Thank to kRON for clearing this up for me. I'd never thought to compare a number to a dict
before and comparison of numbers is one of those things that's so obvious that it's easy to overlook.
这篇关于为什么在python 2.x中int(50)< str(5)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!