Python:最大/最小内置函数取决于参数顺序 [英] Python: max/min builtin functions depend on parameter order
问题描述
max(float('nan'), 1)
计算结果为 nan
max(1, float('nan'))
计算结果为 1
这是预期的行为吗?
感谢您的回答.
max
在可迭代对象为空时引发异常.当 nan
存在时,为什么 Python 的 max
不会引发异常?或者至少做一些有用的事情,比如返回 nan
或忽略 nan
.目前的行为非常不安全,看起来完全不合理.
max
raises an exception when the iterable is empty. Why wouldn't Python's max
raise an exception when nan
is present? Or at least do something useful, like return nan
or ignore nan
. The current behavior is very unsafe and seems completely unreasonable.
我发现了这种行为的更令人惊讶的后果,所以我刚刚发布了一个 相关问题.
I found an even more surprising consequence of this behavior, so I just posted a related question.
推荐答案
In [19]: 1>float('nan')
Out[19]: False
In [20]: float('nan')>1
Out[20]: False
浮点数nan
既不大于也不小于整数1
.max
从选择第一个元素开始,只有当它找到一个严格更大的元素时才替换它.
The float nan
is neither bigger nor smaller than the integer 1
.
max
starts by choosing the first element, and only replaces it when it finds an element which is strictly larger.
In [31]: max(1,float('nan'))
Out[31]: 1
由于nan
不大于1,返回1.
Since nan
is not larger than 1, 1 is returned.
In [32]: max(float('nan'),1)
Out[32]: nan
由于1不大于nan
,所以返回nan
.
Since 1 is not larger than nan
, nan
is returned.
附注.请注意,np.max
对 float('nan')
的处理方式不同:
PS. Note that np.max
treats float('nan')
differently:
In [36]: import numpy as np
In [91]: np.max([1,float('nan')])
Out[91]: nan
In [92]: np.max([float('nan'),1])
Out[92]: nan
但是如果你想忽略np.nan
s,你可以使用np.nanmax
:
but if you wish to ignore np.nan
s, you can use np.nanmax
:
In [93]: np.nanmax([1,float('nan')])
Out[93]: 1.0
In [94]: np.nanmax([float('nan'),1])
Out[94]: 1.0
这篇关于Python:最大/最小内置函数取决于参数顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!