我正在使用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])
只是对刚才所说的稍加补充。
values.index(min(values))似乎返回min的最小索引。下面的语句将获得最大索引:
values.reverse()
(values.index(min(values)) + len(values) - 1) % len(values)
values.reverse()
如果原地反转的副作用不重要,最后一行可以省略。
遍历所有发生的事件
indices = []
i = -1
for _ in range(values.count(min(values))):
i = values[i + 1:].index(min(values)) + i + 1
indices.append(i)
为了简洁起见。在循环之外缓存min(values)和values.count(min)可能是一个更好的主意。
使用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])