基于min函数的比较 [英] Comparison on the basis of min function
问题描述
对于python中的列表,min函数究竟是如何工作的?
How exactly does the min function work for lists in python ?
例如
num = [1,2,3,4,[1,2,3]]
num2 = [1,2,3,4,5]
min(num,num2)
给出 num2
作为结果.是基于比较值还是基于长度?
gives num2
as the result. Is the comparison value based or length based ?
推荐答案
第一件事 - 当用 min
比较两个列表时,按顺序比较元素.所以它比较 1
和 1
,2
和 2
... 和 5
> 与 [1,2,3]
.
First thing - when comparing two lists with min
, elements are compared in order. So it is comparing 1
with 1
, 2
with 2
... and 5
with [1,2,3]
.
其次,在python 2中,允许比较不相等的类型,并给出任意但一致"的排序.引用 docs:
Second, in python 2, unequal types are allowed to be compared, and give an "arbitrary, but consistent" ordering. Quoth the docs:
运算符 <、>、==、>=、<= 和 != 比较两个对象.对象不必具有相同的类型.如果两者都是数字,它们被转换为通用类型.否则,不同的对象类型总是比较不相等,并且顺序一致但随意.
The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily.
...
(这个不寻常的比较定义被用来简化操作的定义,如排序和 in 和 not in 运算符.以后不同类型对象的比较规则是可能会改变.)
(This unusual definition of comparison was used to simplify the definition of operations like sorting and the in and not in operators. In the future, the comparison rules for objects of different types are likely to change.)
至少在 cPython 中,这种比较相当于比较代表各自类型的字符串.因此:
In cPython, at least, this comparison is equivalent to comparing the strings that represent their respective types. Therefore:
5 < [1,2,3]
Out[8]: True
因为 'int' <'列表'
.我相信这是一个实现细节,应该强调这种排序的随意性.
because 'int' < 'list'
. I believe this is an implementation detail, the arbitrariness of this ordering should be stressed.
幸运的是,在 python 3 中,这种愚蠢的行为被 TypeError
取代.
Thankfully in python 3 this silliness is replaced with TypeError
.
这篇关于基于min函数的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!