Python 如何在列表中查找多个最大值项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21893808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find multiple max value items in a list
提问by user3324536
I'm trying to figure out how I can take a list of integers and return all the items in that list into another list as their max value, but with their index.
我试图弄清楚如何获取一个整数列表并将该列表中的所有项目作为它们的最大值返回到另一个列表中,但带有它们的索引。
So I need to be able to do this without using enumeration, lambda, numpy, or anything of that sort. It has to be really basic methods for lists. Basically, things like append, max, etc. . . If for statements are fine too.
所以我需要能够在不使用枚举、lambda、numpy 或任何类似的东西的情况下做到这一点。它必须是列表的真正基本方法。基本上,诸如附加、最大值等之类的东西。. 如果 for 语句也可以。
To clarify what I'm trying to do, say I have a list: [4, 34, 0, 0, 6, 34, 1]I want it to return [1, 5]
为了澄清我正在尝试做的事情,请说我有一个列表:[4, 34, 0, 0, 6, 34, 1]我希望它返回[1, 5]
回答by rokuingh
There are better ways, but if you really want to make it hard..
有更好的方法,但如果你真的想让它变得困难..
max_val = max(funny_list)
i = 0
ind = []
for val in funny_list:
if val == max_val:
ind.append(i)
i = i + 1
回答by Fredrik Pihl
Simplest approach:
最简单的方法:
in [24]: a = [4, 34, 0, 0, 6, 34, 1]
In [25]: j=0
In [26]: M=[]
In [27]: m = max(a)
In [28]: for i in a:
if i==m:
M.append(j)
j+=1
....:
In [29]: M
Out[29]: [1, 5]
Using list-comprehension and enumerate, the above can be shortened to:
使用列表理解和枚举,以上可以缩短为:
In [30]: [i for i, x in enumerate(a) if x == max(a)]
Out[30]: [1, 5]
回答by jonrsharpe
A "fully manual" approach, using none of those pesky standard library functions:
一种“完全手动”的方法,不使用那些讨厌的标准库函数:
def get_max_indices(vals):
maxval = None
index = 0
indices = []
while True:
try:
val = vals[index]
except IndexError:
return indices
else:
if maxval is None or val > maxval:
indices = [index]
maxval = val
elif val == maxval:
indices.append(index)
index = index + 1
What it loses in brevity, it gains in... not much.
它在简洁方面失去了什么,它得到了......不多。

