在列表中查找最大值及其索引的 Pythonic 方法? [英] Pythonic way to find maximum value and its index in a list?

查看:46
本文介绍了在列表中查找最大值及其索引的 Pythonic 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想要一个列表中的最大值,我可以写max(List),但是如果我还需要最大值的索引怎么办?

If I want the maximum value in a list, I can just write max(List), but what if I also need the index of the maximum value?

我可以这样写:

maximum=0
for i,value in enumerate(List):
    if value>maximum:
        maximum=value
        index=i

但对我来说它看起来很乏味.

But it looks tedious to me.

如果我写:

List.index(max(List))

然后它会迭代列表两次.

Then it will iterate the list twice.

有没有更好的方法?

推荐答案

有很多选项,例如:

import operator
index, value = max(enumerate(my_list), key=operator.itemgetter(1))

这篇关于在列表中查找最大值及其索引的 Pythonic 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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