如果是平局,Python会选择哪个最大值? [英] Which maximum does Python pick in the case of a tie?

查看:62
本文介绍了如果是平局,Python会选择哪个最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When using the max() function in Python to find the maximum value in a list (or tuple, dict etc.) and there is a tie for maximum value, which one does Python pick? Is it random?

例如,如果一个人有一个元组列表,并且根据元组的第一个元素选择一个最大值(使用key=),但是有不同的第二个元素,则这是有意义的. Python如何决定选择哪个最大?

This is relevant if, for instance, one has a list of tuples and one selects a maximum (using a key=) based on the first element of the tuple but there are different second elements. How does Python decide which one to pick as the maximum?

推荐答案

它选择看到的第一个元素.请参见 max() 的文档:

It picks the first element it sees. See the documentation for max():

如果最多有多个项目,则该函数将返回遇到的第一个项目.这与其他排序稳定性保存工具(如sorted(iterable, key=keyfunc, reverse=True)[0]heapq.nlargest(1, iterable, key=keyfunc))一致.

在源代码中,此实现./Python/bltinmodule.cbuiltin_max 封装,其中包装了更通用的min_max函数.

In the source code this is implemented in ./Python/bltinmodule.c by builtin_max, which wraps the more general min_max function.

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

min_max will iterate through the values and use PyObject_RichCompareBool to see if they are greater than the current value. If so, the greater value replaces it. Equal values will be skipped over.

结果是,如果出现平局,将选择第一个最大值.

The result is that the first maximum will be chosen in the case of a tie.

这篇关于如果是平局,Python会选择哪个最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆