簡體   English   中英

如何在二維列表的一行中找到最大值及其索引?

[英]How to find max value and its index in a row of 2d list?

我有一個二維列表。 我想找到每行的最大值及其索引。 這是清單

q_table = [[0.16,  0.40,  0.61,  0.48,  0.20],
           [0.42,  0.79,  0.64,  0.54,  0.52],
           [0.64,  0.64,  0.24,  0.93,  0.43],
           [0.33,  0.54,  0.61,  0.43,  0.29],
           [0.25,  0.56,  0.42,  0.69,  0.62]]

Output:

0.61 2
0.79 1
0.93 3
0.61 2
0.69 3

# I'm using python 3.8

先感謝您

正如評論中所建議的,您可以使用 max 從列表中獲取最大值,使用 argmax 獲取 position。

np.argmax(q_table, axis=1) #returns list of position of max value in each list.
np.max(q_table, axis=1)  # return list of max value in each  list.

然后,您可以使用 zip function 將兩個列表一起迭代並將 output 存儲在列表列表中

import numpy as np
max_list_with_position=[ [x,y] for x,y in zip(np.argmax(q_table, axis=1),np.max(q_table, axis=1))]
print(max_list_with_position)

output:

[[2, 0.61], [1, 0.79], [3, 0.93], [2, 0.61], [3, 0.69]]
q_table = [[0.16,  0.40,  0.61,  0.48,  0.20],
           [0.42,  0.79,  0.64,  0.54,  0.52],
           [0.64,  0.64,  0.24,  0.93,  0.43],
           [0.33,  0.54,  0.61,  0.43,  0.29],
           [0.25,  0.56,  0.42,  0.69,  0.62]]

rows_count = len(q_table) # to count number of rows
for i in range(rows_count):
    a_row = q_table[i] # taking each row in a variable
    max_value = max(a_row) # find mad value in a single row
    index = a_row.index(max_value) # find the max value's index of a single row
    print("The max value ",max_value, " and Index in ",index)

如果有更好的方法建議。

這是output,

The max value  0.61  and Index in  2
The max value  0.79  and Index in  1
The max value  0.93  and Index in  3
The max value  0.61  and Index in  2
The max value  0.69  and Index in  3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM