以下是一些標題選項,請記住問答格式和文章的重點: 直接、簡潔: * 如何找到Python清單中最大值或最小值的索引?

DDD
發布: 2024-10-28 16:40:03
原創
824 人瀏覽過

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

使用max()/min() 找出清單中最大值或最小值的索引

使用Python 內建函數時對於minimax 演算法的max() 和min() 函數,有必要檢索傳回的max 或min 項目的索引。這樣可以辨識產生所需值的特定動作。

原始程式碼:

<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>
登入後複製

解:

要取得最小值或最大值的索引,請使用以下方法:

<code class="python">import functools

index_min = min(range(len(values)), key=functools.cmp_to_key(lambda x, y: values[x] - values[y]))</code>
登入後複製

或者,如果使用NumPy 可行:

<code class="python">import numpy as np
index_min = np.argmin(values)</code>
登入後複製

基準結果:

以下基準測試結果是在在運行Python 2.7 的機器上獲得的:

[比較純Python 解決方案(藍色)、NumPy 解決方案(紅色)和itemgetter() 的基準測試結果圖像基於解決方案(黑色)]

結論:

建議的解決方案是不需要導入額外模組或使用枚舉的解決方案,因為它在大多數情況下。然而,對於大型列表,基於 NumPy 的方法可能是最佳選擇。

以上是以下是一些標題選項,請記住問答格式和文章的重點: 直接、簡潔: * 如何找到Python清單中最大值或最小值的索引?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!