Finding the Index of the Maximum or Minimum Value in a List Using max()/min()
When employing Python's built-in max() and min() functions for minimax algorithms, it becomes necessary to retrieve the index of the returned max or min item. This allows identification of the specific move that produced the desired value.
Original Code:
<code class="python">for i in range(9): new_board = current_board.new_board_with_move([i / 3, i % 3], player) if new_board: temp = min_max(new_board, depth + 1, not is_min_level) values.append(temp) if is_min_level: return min(values) else: return max(values)</code>
Solution:
To obtain the index of the min or max value, utilize the following approach:
<code class="python">import functools index_min = min(range(len(values)), key=functools.cmp_to_key(lambda x, y: values[x] - values[y]))</code>
Alternatively, if using NumPy is feasible:
<code class="python">import numpy as np index_min = np.argmin(values)</code>
Benchmark Results:
The following benchmark results were obtained on a machine running Python 2.7:
[Image of benchmark results comparing pure Python solution (blue), NumPy solution (red), and itemgetter()-based solution (black)]
Conclusion:
The recommended solution is the one that does not require importing additional modules or using enumerations, as it provides superior speed in most cases. Nevertheless, for large lists, a NumPy-based approach may be optimal.
The above is the detailed content of Here are a few title options, keeping in mind the question-and-answer format and the article\'s focus: Direct & Concise: * How to Find the Index of the Maximum or Minimum Value in a Python List?. For more information, please follow other related articles on the PHP Chinese website!