Skip to main content
 首页 » 编程设计

python之max 和 np.max 的区别

2024年12月31日10softidea

我对仅使用 max(list array) 和 np.max(list array) 之间的区别有疑问。

这里唯一的区别是 Python 返回代码所需的时间吗?

请您参考如下方法:

它们在边缘情况下可能不同,例如包含 NaN 的列表。

import numpy as np 
a = max([2, 4, np.nan])     # 4 
b = np.max([2, 4, np.nan])  # nan 

NumPy 在这种情况下传播 NaN,而 Python 的 max 的行为不太确定。

关于数据类型还有一些微妙的问题:

a = max([10**n for n in range(20)])     # a is an integer 
b = np.max([10**n for n in range(20)])  # b is a float 

当然,运行时间差异记录在 numpy.max or max ? Which one is faster? 中

通常,应该对 Python 列表使用 max,对 NumPy 数组使用 np.max 以尽量减少意外的数量。例如,我的第二个示例并不是真正关于 np.max,而是关于数据类型转换:要使用 np.max,首先将列表转换为 NumPy 数组,但是10**19 之类的元素太大,无法用 NumPy 整数类型表示,因此它们变成了 float 。