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

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

问题描述

所以说我有一个列表:

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

所以这里的最大数量显然是 58,但我不只是想返回 one 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.

有什么建议吗?另外,我想坚持使用简单的方法,例如sortmaxlen 等...

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

推荐答案

您可以使用 max:

You can determine the maxval with max:

maxval = max(my_list)

然后使用 enumerate列表理解:

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

对于你的例子,我得到

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

<小时>

根据 Keyser 的建议,您可以通过执行以下操作来保存对列表的迭代两次(一次确定 maxval,一次找到匹配的 indexes):


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天全站免登陆