gpt4 book ai didi

python - 在平局的情况下,Python 选择哪个最大值?

转载 作者:IT老高 更新时间:2023-10-28 21:40:44 27 4
gpt4 key购买 nike

当在 Python 中使用 max() 函数来查找列表(或元组、字典等)中的最大值并且最大值存在平局时,Python 选择哪一个?是随机的吗?

这是相关的,例如,一个人有一个元组列表,一个人根据元组的第一个元素选择最大值(使用 key=),但有不同的第二个元素。 Python 如何决定选择哪一个作为最大值?

最佳答案

它选择它看到的第一个元素。见 the documentation for max() :

If multiple items are maximal, the function returns the first one encountered. This is consistent with other sort-stability preserving tools such as sorted(iterable, key=keyfunc, reverse=True)[0] and heapq.nlargest(1, iterable, key=keyfunc).

在源代码中实现了 in ./Python/bltinmodule.c by builtin_max ,它包装了 more general min_max function .

min_max 将遍历这些值并使用 PyObject_RichCompareBool查看它们是否大于当前值。如果是这样,则较大的值将替换它。相同的值将被跳过。

结果是在平局的情况下将选择第一个最大值。

关于python - 在平局的情况下,Python 选择哪个最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6783000/

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