python的方法找到最大值和它的索引在一个列表?

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

我可以这样写:

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

但我觉得很乏味。

如果我写:

List.index(max(List))

然后它将迭代该列表两次。

有没有更好的办法?

413521 次浏览

有很多选择,例如:

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

我认为公认的答案很好,但你为什么不明确地说出来呢?我觉得更多的人会理解你的代码,这与PEP 8是一致的:

max_value = max(my_list)
max_index = my_list.index(max_value)

这种方法也比公认的答案快三倍:

import random
from datetime import datetime
import operator


def explicit(l):
max_val = max(l)
max_idx = l.index(max_val)
return max_idx, max_val


def implicit(l):
max_idx, max_val = max(enumerate(l), key=operator.itemgetter(1))
return max_idx, max_val


if __name__ == "__main__":
from timeit import Timer
t = Timer("explicit(l)", "from __main__ import explicit, implicit; "
"import random; import operator;"
"l = [random.random() for _ in xrange(100)]")
print "Explicit: %.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)


t = Timer("implicit(l)", "from __main__ import explicit, implicit; "
"import random; import operator;"
"l = [random.random() for _ in xrange(100)]")
print "Implicit: %.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)

在我的电脑中运行的结果:

Explicit: 8.07 usec/pass
Implicit: 22.86 usec/pass

其他设置:

Explicit: 6.80 usec/pass
Implicit: 19.01 usec/pass

这个答案比@Escualo快33倍,假设列表非常大,并且它已经是一个np.array()。我不得不减少测试运行的次数,因为测试要查看10000000个元素,而不仅仅是100个。

import random
from datetime import datetime
import operator
import numpy as np


def explicit(l):
max_val = max(l)
max_idx = l.index(max_val)
return max_idx, max_val


def implicit(l):
max_idx, max_val = max(enumerate(l), key=operator.itemgetter(1))
return max_idx, max_val


def npmax(l):
max_idx = np.argmax(l)
max_val = l[max_idx]
return (max_idx, max_val)


if __name__ == "__main__":
from timeit import Timer


t = Timer("npmax(l)", "from __main__ import explicit, implicit, npmax; "
"import random; import operator; import numpy as np;"
"l = np.array([random.random() for _ in xrange(10000000)])")
print "Npmax: %.2f msec/pass" % (1000  * t.timeit(number=10)/10 )


t = Timer("explicit(l)", "from __main__ import explicit, implicit; "
"import random; import operator;"
"l = [random.random() for _ in xrange(10000000)]")
print "Explicit: %.2f msec/pass" % (1000  * t.timeit(number=10)/10 )


t = Timer("implicit(l)", "from __main__ import explicit, implicit; "
"import random; import operator;"
"l = [random.random() for _ in xrange(10000000)]")
print "Implicit: %.2f msec/pass" % (1000  * t.timeit(number=10)/10 )

我电脑上的结果:

Npmax: 8.78 msec/pass
Explicit: 290.01 msec/pass
Implicit: 790.27 msec/pass

使用Python的内置库,这非常简单:

a = [2, 9, -10, 5, 18, 9]
max(xrange(len(a)), key = lambda x: a[x])

这告诉max使用自定义函数lambda x: a[x]找到列表[0, 1, 2, ..., len(a)]中最大的数字,这表明0实际上是21实际上是9,等等。

max([(v,i) for i,v in enumerate(my_list)])
max([(value,index) for index,value in enumerate(your_list)]) #if maximum value is present more than once in your list then this will return index of the last occurrence

如果最大值出现在present中不止一次,你想要得到所有的下标,

max_value = max(your_list)
maxIndexList = [index for index,value in enumerate(your_list) if value==max(your_list)]

也许你需要一个排序的列表?

试试这个:

your_list = [13, 352, 2553, 0.5, 89, 0.4]
sorted_list = sorted(your_list)
index_of_higher_value = your_list.index(sorted_list[-1])

下面是一个使用Python内置函数的完整解决方案:

# Create the List
numbers = input("Enter the elements of the list. Separate each value with a comma. Do not put a comma at the end.\n").split(",")


# Convert the elements in the list (treated as strings) to integers
numberL = [int(element) for element in numbers]


# Loop through the list with a for-loop


for elements in numberL:
maxEle = max(numberL)
indexMax = numberL.index(maxEle)


print(maxEle)
print(indexMax)

我建议一个非常简单的方法:

import numpy as np
l = [10, 22, 8, 8, 11]
print(np.argmax(l))
print(np.argmin(l))

希望能有所帮助。

我列了一些大清单。一个是列表,一个是numpy数组。

import numpy as np
import random
arrayv=np.random.randint(0,10,(100000000,1))
listv=[]
for i in range(0,100000000):
listv.append(random.randint(0,9))

使用jupyter笔记本的%%time功能,我可以比较各种事情的速度。

2秒:

%%time
listv.index(max(listv))

54.6秒:

%%time
listv.index(max(arrayv))

6.71秒:

%%time
np.argmax(listv)

103女士:

%%time
np.argmax(arrayv)

Numpy的数组非常快。

列表理解方法:

假设你有一个列表List = [5,2,3,8]

那么[i for i in range(len(List)) if List[i] == max(List)]将是一个python的列表理解方法,用于查找值"i"List[i] == max(List)的地方。

对于作为列表的列表的数组,它很容易扩展,只需执行for循环即可。

例如,使用列表的任意列表“数组”;和初始化"index"作为一个空列表。

array = [[5, 0, 1, 1],
[1, 0, 1, 5],
[0, 1, 6, 0],
[0, 4, 3, 0],
[5, 2, 0, 0],
[5, 0, 1, 1],
[0, 6, 0, 1],
[0, 1, 0, 6]]
index = []


for List in array:
index.append([i for i in range(len(List)) if List[i] == max(List)])
index

输出:[[0], [3], [2], [1], [0], [0], [1], [3]]