python参数顺序问题_Python:max / min内置函数取决于参数顺序

max(float('nan'), 1) evaluates to nan

max(1, float('nan')) evaluates to 1

Is it the intended behavior?

Thanks for the answers.

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

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

Since nan is not larger than 1, 1 is returned.

In [32]: max(float('nan'),1)

Out[32]: nan

Since 1 is not larger than nan, nan is returned.

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

but if you wish to ignore np.nans, 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值