如果我想要一个列表中的最大值,我可以只写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))
然后它将迭代该列表两次。
有没有更好的办法?
当前回答
我建议一个非常简单的方法:
import numpy as np
l = [10, 22, 8, 8, 11]
print(np.argmax(l))
print(np.argmin(l))
希望能有所帮助。
其他回答
有很多选择,例如:
import operator
index, value = max(enumerate(my_list), key=operator.itemgetter(1))
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)]
max([(v,i) for i,v in enumerate(my_list)])
我建议一个非常简单的方法:
import numpy as np
l = [10, 22, 8, 8, 11]
print(np.argmax(l))
print(np.argmin(l))
希望能有所帮助。
下面是一个使用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)