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

我可以这样写:

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

但我觉得很乏味。

如果我写:

List.index(max(List))

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

有没有更好的办法?


当前回答

这个答案比@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内置函数的完整解决方案:

# 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)

列表理解方法:

假设你有一个列表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]]

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

试试这个:

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])
max([(v,i) for i,v in enumerate(my_list)])

有很多选择,例如:

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