gpt4 book ai didi

python - max 和 np.max 的区别

转载 作者:太空宇宙 更新时间:2023-11-04 04:39:46 30 4
gpt4 key购买 nike

我对仅使用 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 。

关于python - max 和 np.max 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50920346/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com