我正在使用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)

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


当前回答

使用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])

其他回答

这可以使用内置的enumerate()和max()函数以及max()函数的可选键参数和一个简单的lambda表达式来实现:

theList = [1, 5, 10]
maxIndex, maxValue = max(enumerate(theList), key=lambda v: v[1])
# => (2, 10)

在max()的文档中,它说key参数需要一个类似list.sort()函数中的函数。请参见如何排序。

对于min()也是一样的。顺便说一下,它返回第一个最大/最小值。

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

df(列).idxmax ()

使用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])

使用numpy数组和argmax()函数

 a=np.array([1,2,3])
 b=np.argmax(a)
 print(b) #2

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

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