Getting the Index of Max/Min Values Returned by max()/min() on Lists
When using Python's max() and min() functions on lists for algorithms like minimax, determining the index of the returned maximum or minimum value is often necessary.
Problem:
You need to find the index of the element in a list that corresponds to the max() or min() value returned, to identify which move produced that value.
Solution:
To retrieve the index of the min() value, utilize the following code:
<code class="python">index_min = min(range(len(values)), key=values.__getitem__)</code>
This method eliminates the need for modules like operator or enumerate, and it also outperforms solutions involving itemgetter().
For numpy arrays, consider using:
<code class="python">import numpy as np index_min = np.argmin(values)</code>
This is faster if the list is large enough and memory consumption is acceptable.
Benchmark:
The benchmark below compares the efficiency of the two proposed solutions:
[Image showing a graph with runtimes for the different methods]
The blue line represents the pure Python solution, while the red line uses numpy. The black line is the reference implementation using itemgetter().
For large lists, the numpy solution is significantly faster. However, for smaller lists, the pure Python solution may be more efficient.
The above is the detailed content of How to Efficiently Find the Index of Max/Min Values in Python Lists?. For more information, please follow other related articles on the PHP Chinese website!