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

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]]

输出:

0.61 2
0.79 1
0.93 3
0.61 2
0.69 3

# I'm using python 3.8

提前致谢

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)

如果有更好的方法建议。

这是输出,

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

如评论中所建议,您可以使用 max 从列表中获取最大值,并使用 argmax 获取位置。

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 函数将两个列表一起迭代并将输出存储在列表列表中

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)

输出:

[[2, 0.61], [1, 0.79], [3, 0.93], [2, 0.61], [3, 0.69]]