如果我想要一个列表中的最大值,我可以只写max(list),但如果我还需要最大值的索引呢?
我可以这样写:
maximum=0
for i,value in enumerate(List):
if value>maximum:
maximum=value
index=i
但我觉得很乏味。
如果我写:
List.index(max(List))
然后它将迭代该列表两次。
有没有更好的办法?
如果我想要一个列表中的最大值,我可以只写max(list),但如果我还需要最大值的索引呢?
我可以这样写:
maximum=0
for i,value in enumerate(List):
if value>maximum:
maximum=value
index=i
但我觉得很乏味。
如果我写:
List.index(max(List))
然后它将迭代该列表两次。
有没有更好的办法?
当前回答
列表理解方法:
假设你有一个列表list = [5,2,3,8]
那么[i for i in range(len(List)) if List[i] == max(List)]将是一个python式的列表理解方法,用于查找List[i] == max(List)中的值“i”。
对于作为列表的列表的数组,它很容易扩展,只需执行for循环即可。
例如,使用列表的任意列表“array”并将“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]]
其他回答
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)]
我建议一个非常简单的方法:
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的数组非常快。
max([(v,i) for i,v in enumerate(my_list)])
使用Python的内置库,这非常简单:
a = [2, 9, -10, 5, 18, 9]
max(xrange(len(a)), key = lambda x: a[x])
这告诉max找到列表中最大的数字[0,1,2,…], len(a)],使用自定义函数lambda x: a[x],这表明0实际上是2,1实际上是9,等等。