python - 为什么 `max` 和 `min` 在使用空可迭代对象调用时不返回适当的无穷大?

标签 python python-3.x math reduce

我正在写一个 blog article关于reduce是什么,它是如何工作的,以及它背后隐藏的功能,在某个点上我讲了sumallanymaxmin,所有缩减。

然后,我讲一下 reduce 如何接受第三个参数,即初始值,它应该是您正在使用的函数的标识元素。 然后,我继续展示一些专门的缩减,其中包含标识元素:

>>> sum([])
0
>>> import math
>>> math.prod([])
1
>>> all([])
True

那么,为什么 maxmin 在调用空迭代器时会抛出错误, 他们的操作什么时候身份元素?

>>> max([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence

我们可以执行 float("-inf"),那么为什么这不是 max([]) 返回的值?同样,为什么 min([]) 不返回 float("inf")

最佳答案

因为 min()max() 接受任何类型,它们可能无法与 float 进行比较。例如,字符串:

>>> min('a', 'b')
'a'
>>> min(float('-inf'), 'a', 'b')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'float'

如果你想要你正在谈论的行为,你可以使用默认参数:

>>> min([], default=float('-inf'))
-inf

也就是说,min()max() 比你提到的其他函数有更广泛的应用。 sum()math.prod() 主要用于数字,因此给它们数字起始值是有意义的。不过,您可以使用它们的 start 参数更改它。下面是一些带有列表的示例,尽管它们不是很地道。

>>> math.prod([2, 3], start=['a'])  # better: ['a'] * math.prod([2, 3])
['a', 'a', 'a', 'a', 'a', 'a']
>>> sum([['a'], ['b']], start=[])  # better: list(itertools.chain(['a'], ['b']))
['a', 'b']

关于python - 为什么 `max` 和 `min` 在使用空可迭代对象调用时不返回适当的无穷大?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67894680/

相关文章:

python - pandas DataFrame 连接/更新 ("upsert")?

python-3.x - 具有相同输入的两个 python(3) 类(扩展一个 python 类)

python - 适用于 python 3.x 的 Asterisk ami

c# - 20 位整数数学

Python - 将列值分组到类中

python - Django 测试客户端 post() 返回 302,尽管 View 的 post() 出错

python - 如何随机生成非常小的数字?

algorithm - 在 3D 中搜索点之间的 K 个最小距离

Python——Matplotlib 用户通过鼠标输入进行绘图

python - 使用 Python 解析网页的搜索结果