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?

DDD
Release: 2024-10-28 16:40:03
Original
824 people have browsed it

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?
* Efficiently Obtaining the Index of the Max/Min Value in

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>
Copy after login

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>
Copy after login

Alternatively, if using NumPy is feasible:

<code class="python">import numpy as np
index_min = np.argmin(values)</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!