简体   繁体   English

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

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

I have a 2D list.我有一个二维列表。 I want to find the max value and its index of each row.我想找到每行的最大值及其索引。 Here is the 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: Output:

0.61 2
0.79 1
0.93 3
0.61 2
0.69 3

# I'm using python 3.8

Thank You in Advance先感谢您

as suggested in comments you can use max to get the max values from your list and argmax for getting the position.正如评论中所建议的,您可以使用 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.

you can then use zip function to iterate both the list together and store the output in list of 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: 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)

If there is a better way do suggest.如果有更好的方法建议。

and here is the output,这是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