我正在使用Python的max和min函数对列表进行minimax算法,我需要max()或min()返回值的索引。换句话说,我需要知道哪一步棋产生了最大(第一个玩家的回合)或最小(第二个玩家的回合)值。

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)

我需要能够返回最小值或最大值的实际索引,而不仅仅是值。


当前回答

如果你想在一个数字列表中找到max的下标(这似乎是你的情况),那么我建议你使用numpy:

import numpy as np
ind = np.argmax(mylist)

其他回答

就这么简单:

stuff = [2, 4, 8, 15, 11]

index = stuff.index(max(stuff))
if is_min_level:
    return values.index(min(values))
else:
    return values.index(max(values))

我认为最好的方法是将列表转换为numpy数组并使用这个函数:

a = np.array(list)
idx = np.argmax(a)

在你得到最大值后,试试这个:

max_val = max(list)
index_max = list.index(max_val)

比一大堆选项简单多了。

为什么要先添加索引,然后反转它们呢?Enumerate()函数只是zip()函数用法的一个特例。让我们以适当的方式来使用它:

my_indexed_list = zip(my_list, range(len(my_list)))

min_value, min_index = min(my_indexed_list)
max_value, max_index = max(my_indexed_list)