我正在使用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_val = max(list)
index_max = list.index(max_val)

比一大堆选项简单多了。

其他回答

我对此也很感兴趣,并使用perfplot(我的一个爱好项目)比较了一些建议的解决方案。

事实证明

min(range(len(a)), key=a.__getitem__)

是用于小型和大型列表的最快方法。

在以前的版本中,np。阿格明过去常吃蛋糕。)


生成图的代码:

import numpy as np
import operator
import perfplot


def min_enumerate(a):
    return min(enumerate(a), key=lambda x: x[1])[0]


def min_enumerate_itemgetter(a):
    min_index, min_value = min(enumerate(a), key=operator.itemgetter(1))
    return min_index


def getitem(a):
    return min(range(len(a)), key=a.__getitem__)


def np_argmin(a):
    return np.argmin(a)


b = perfplot.bench(
    setup=lambda n: np.random.rand(n).tolist(),
    kernels=[
        min_enumerate,
        min_enumerate_itemgetter,
        getitem,
        np_argmin,
    ],
    n_range=[2**k for k in range(15)],
)
b.show()

熊猫现在有一个更温和的解决方案,试试吧:

df(列).idxmax ()

https://docs.python.org/3/library/functions.html#max

如果有多个最大项,则函数返回遇到的第一个项。这与其他保持排序稳定性的工具是一致的,例如sorted(iterable, key=keyfunc, reverse=True)[0]

要获得比第一次遇到的更多信息,请使用sort方法。

import operator

x = [2, 5, 7, 4, 8, 2, 6, 1, 7, 1, 8, 3, 4, 9, 3, 6, 5, 0, 9, 0]

min = False
max = True

min_val_index = sorted( list(zip(x, range(len(x)))), key = operator.itemgetter(0), reverse = min )

max_val_index = sorted( list(zip(x, range(len(x)))), key = operator.itemgetter(0), reverse = max )


min_val_index[0]
>(0, 17)

max_val_index[0]
>(9, 13)

import ittertools

max_val = max_val_index[0][0]

maxes = [n for n in itertools.takewhile(lambda x: x[0] == max_val, max_val_index)]

使用numpy模块的函数numpy.where

import numpy as n
x = n.array((3,3,4,7,4,56,65,1))

最小值指数:

idx = n.where(x==x.min())[0]

最大值指数:

idx = n.where(x==x.max())[0]

事实上,这个函数要强大得多。你可以提出各种布尔运算 数值在3至60之间的指数:

idx = n.where((x>3)&(x<60))[0]
idx
array([2, 3, 4, 5])
x[idx]
array([ 4,  7,  4, 56])

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

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

比一大堆选项简单多了。