如何在带有绑定数字的列表中找到最大数字 [英] How to find the max number(s) in a list with tied numbers
问题描述
所以说我有一个列表:
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.
有什么建议吗?另外,我想坚持使用简单的方法,例如sort
、max
、len
等...
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)
indices = [index for index, val in enumerate(my_list) if val == maxval]
对于你的例子,我得到
maxval == 58
indices = [5, 10, 11]
<小时>
根据 Keyser 的建议,您可以通过执行以下操作来保存对列表的迭代两次(一次确定 maxval
,一次找到匹配的 index
es):
As per Keyser's suggestion, you could save iterating over the list twice (once to determine maxval
, once to find matching index
es) 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屋!