Python Max函数 [英] Python Max Function

查看:63
本文介绍了Python Max函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当列表中的项目不是同一类型时,max函数如何工作?

How does the max function work when items in a list are not of the same type?

例如,以下代码返回[1,'3']

For example the following code returns [1,'3']

max([1,52,53],[1,'3']) => [1,'3']

推荐答案

在Python2中,不同类型的对象的默认比较是使用其类型的 id 进行比较(通过投射对象获得)指向整数的指针).这里是到源的链接: http://hg.python. org/cpython/file/2.7/Objects/object.c#l757

In Python2, the default comparison for objects of different types is to compare using the id of their types (obtained by casting the object pointers to integers). Here a link to the source: http://hg.python.org/cpython/file/2.7/Objects/object.c#l757

在我的构建中,这是类型的顺序:

On my build, here is the ordering of types:

>>> 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'>]

数字(复数除外)具有比较方法,该方法允许基于数值进行交叉类型比较(即,浮点数可以与整数进行比较).

Numbers (except for complex) have compare methods that allow cross type comparison based on numeric value (i.e. a float can be compared with an int).

对象是特殊的.它比其他所有东西都少.

The None object is special. It compares less than everything else.

要查看全部内容,请使用 sorted 查看顺序:

To see it all put together, use sorted to see the ordering:

>>> 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']

这篇关于Python Max函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆