Sag*_*tel 3 python max python-2.7
当列表中的项目不是同一类型时,max函数如何工作?
例如,以下代码返回[1,'3']
max([1,52,53],[1,'3']) => [1,'3']
Run Code Online (Sandbox Code Playgroud)
在Python2中,不同类型对象的默认比较是使用其类型的id进行比较(通过将对象指针转换为整数获得).这里是源代码的链接:http: //hg.python.org/cpython/file/2.7/Objects/object.c#l757
在我的构建中,这是类型的排序:
>>> sorted([bool, int, float, long, list, tuple, dict, str, unicode])
[<type 'bool'>, <type 'float'>, <type 'int'>, <type 'list'>, <type 'long'>,
<type 'dict'>, <type 'str'>, <type 'tuple'>, <type 'unicode'>]
Run Code Online (Sandbox Code Playgroud)
数字(复杂除外)具有比较方法,允许基于数值的交叉类型比较(即浮点数可以与int进行比较).
该无对象是特殊的.它比其他所有东西都要少.
要将它们全部放在一起,请使用sorted来查看排序:
>>> sorted(zoo)
[None, -5, -5.0, 0, 0.0, -0.0, False, True, 10, 10.0, 11.5, {},
{'abc': 10}, {'lmno': 20}, [], [1, 2], [1, 2, 3], [1, [2, 3]],
'', u'', 'alpha', u'alpha', 'bingo', 'cat', (), (1, 2),
(1, 2, 3), (1, (2, 3)), u'bingo', u'cat']
Run Code Online (Sandbox Code Playgroud)
在Python 2中,使用特殊逻辑通过类型的字符串表示来比较不同类型的对象.有关详细信息,请参阅Raymond的答案.
在Python 3中,此代码将引发异常:
Traceback (most recent call last):
File "prog.py", line 1, in <module>
max([1,52,53],[1,'3'])
TypeError: unorderable types: str() > int()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4218 次 |
| 最近记录: |