Say that you have a list values = [3,6,1,5]
, and need the index of the smallest element, ie index_min = 2
in this case.
(假设您有一个列表values = [3,6,1,5]
,并且需要最小元素的索引,在这种情况下,即index_min = 2
。)
Avoid the solution with itemgetter()
presented in the other answers, and use instead
(避免使用其他答案中出现的itemgetter()
解决方案,而改用)
index_min = min(xrange(len(values)), key=values.__getitem__)
because it doesn't require to import operator
nor to use enumerate
, and it is always faster(benchmark below) than a solution using itemgetter()
.
(因为它不需要import operator
或使用enumerate
,并且它总是比使用itemgetter()
的解决方案更快(下面的基准itemgetter()
。)
If you are dealing with numpy arrays or can afford numpy
as a dependency, consider also using
(如果您正在处理numpy数组或可以负担numpy
作为依赖项,请考虑同时使用)
import numpy as np
index_min = np.argmin(values)
This will be faster than the first solution even if you apply it to a pure Python list if:
(即使在以下情况下将其应用于纯Python列表,也将比第一个解决方案更快。)
as this benchmark points out:
(正如该基准所指出的:)
I have run the benchmark on my machine with python 2.7 for the two solutions above (blue: pure python, first solution) (red, numpy solution) and for the standard solution based on itemgetter()
(black, reference solution).
(我已经使用python 2.7在机器上运行了基准测试,用于上述两个解决方案(蓝色:纯python,第一个解决方案)(红色,numpy解决方案)以及基于itemgetter()
的标准解决方案(黑色,参考解决方案)。)
The same benchmark with python 3.5 showed that the methods compare exactly the same of the python 2.7 case presented above (与python 3.5相同的基准测试表明,这些方法与上述python 2.7情况完全相同)