[英]Finding index of smallest element in list only for elements at a certain index
說我有以下列表:
possible_moves = [0, 1, 2, 3]
q_array = [4, 2, 3, 7, -10]
我想獲得的最小元素的索引q_array
只在指數中的元素possible_moves
。 因此,兩個列表的輸出應為1。
我使用下面的代碼實現了它,但是它實際上並不是很Pythonic。
best_value = q_array[random.choice(possible_moves)]
for move in possible_moves:
if q_array[move] <= best_value:
best_value = q_array[move]
move_chosen = move
return move_chosen
編輯:返回的值應該是最小值的索引,而不是值本身。 在上面的例子中,則返回1,因為它是最小的值與在索引中的元素中的索引possible_moves
建立僅包含所需元素的列表理解,然后找到該列表的min()
:
min([q_array[x] for x in possible_moves])
您可以使用min
功能上possible_moves
與列表__getitem__
的方法q_array
名單的關鍵功能:
min(possible_moves, key=q_array.__getitem__)
返回值: 1
將數據放入字典,然后獲取具有最小值的密鑰。
>>> d = {i: q_array[i] for i in possible_moves}
>>> move_chosen = min(d, key=d.get)
1
這類似於blhsing的答案 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.