[英]Get the last index with same max values in a list
I have the following list: 我有以下列表:
a = [100, 34, 2, 100]
I want the index of the largest value: 我想要最大值的索引:
$ a.index(max(a))
Returns: 0
What is the Pythonic way of getting the last index (with the largest value) in this case 3
. 在这种情况下,获得最后一个索引(具有最大值)的Pythonic方法是什么
3
。
(Since the largest value is repeated multiple times.) (因为最大值重复多次。)
I think this might work for you. 我认为这可能对你有用。
len(a) - a[::-1].index(max(a)) - 1
a[::-1]
is the Pythonic way to reverse the list, and then the index
function will find the "first" time that max(a)
occurs in the reversed list, which will be the last time it occurs in the original list. a[::-1]
是反转列表的Pythonic方法,然后index
函数将找到max(a)
在反转列表中出现的“第一”时间,这将是它最后一次出现在原始列表中名单。
Another way to do it could be: 另一种方法可能是:
def last_max_index2(s):
m_index = m = None
for i, elem in enumerate(s):
if elem >= m:
m, m_index = elem, i
return m_index
last_max_index2
has the advantage that it is calculating the max as it goes, and hence only needs one pass over the array. last_max_index2
的优点在于它正在计算max,因此只需要在数组上进行一次传递。 But it's more of an algorithm you would see written in C++ or Java, and less in Python. 但它更像是一种用C ++或Java编写的算法,而在Python中则更少。 Often this is correct: the shorter ways that rely on built-ins are better.
通常这是正确的:依赖内置插件的较短方式更好。
However, I think this is a much more readable and intuitive approach than any solution using reduce
or a single-liner with enumerate
and keys with lambdas. 不过,我认为这是比使用任何解决方案更具有可读性和直观的方法
reduce
或单内胆采用enumerate
和按键与lambda表达式。 Those solutions will only be readily understandable by very familiar Python programmers. 只有非常熟悉的Python程序员才能理解这些解决方案。
And a solution like that in the comments is very obfuscated: 并且评论中的解决方案非常混淆:
last_max_index3 = lambda s: max((x, i) for i, x in enumerate(s))[1]
I know most folks familiar with Python would disagree, but I think this code is so misdirectional to a Python beginner that it's actually harmful to do it this way, regardless of one-liner-ness, use of enumerate
, and small number of characters typed. 我知道大多数熟悉Python的人会不同意,但我认为这段代码对于Python初学者来说是如此误导,以这种方式实际上是有害的 ,无论是单行,使用
enumerate
,还是输入少量字符。
Not sure that it is very pythonic: 不确定它是非常pythonic:
l = [100, 34, 2, 100]
>>> reduce(lambda m, p: p if p[1]>=m[1] else m, enumerate(l))
(3, 100)
FWIW, here's another option. FWIW,这是另一种选择。 I dare say more pythonic than the accepted answer
我敢说比你接受的答案更pythonic
max(reversed(xrange(len(a))), key=a.__getitem__)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.