如何在带有数字的列表中查找最大数量 [英] How to find the max number(s) in a list with tied numbers

查看:150
本文介绍了如何在带有数字的列表中查找最大数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以说我有一个列表如下:

So say I have a list like:

my_list = [12, 13, 51, 21, 22, 58, 45.1, 34.2, 56, 6, 58, 58] 

所以这个中的最大数字显然是58 ,但我不只是想返回一个 58,我想要一个包含最大数量的所有索引的列表。

So the max number in this is obviously 58, but I don't just want to return one 58, I want a list of all the indexes that have that max number.

基本上为此,我想要结果 [5,10,11]

Basically for this I want the result [5, 10, 11]

我知道如果我想要最大数量我可以做 my_list.index(max(my_list))但这只会给我第一个索引。

I know that if I want the max number I can do my_list.index(max(my_list)) but that will simply give me the first index.

任何提示?另外,我想坚持使用简单的方法,例如 sort max len 等...

Any tips? Also, I want to stick to simple methods such as sort, max, len, etc...

推荐答案

您可以确定 maxval max

You can determine the maxval with max:

maxval = max(my_list)

然后使用 <获取索引code>枚举 列表理解

indices = [index for index, val in enumerate(my_list) if val == maxval]

对于你的例子,我得到

maxval == 58
indices = [5, 10, 11]






根据Keyser的建议,你可以节省迭代次数e list两次(一次确定 maxval ,一次找到匹配的 index es):


As per Keyser's suggestion, you could save iterating over the list twice (once to determine maxval, once to find matching indexes) by doing:

maxval = None
for index, val in enumerate(my_list):
    if maxval is None or val > maxval:
        indices = [index]
        maxval = val
    elif val == maxval:
        indices.append(index)

这篇关于如何在带有数字的列表中查找最大数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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