Python 如何在二维列表的行中查找最大值及其索引?
我有一个2D列表。我想找到每行的最大值及其索引。 这是名单Python 如何在二维列表的行中查找最大值及其索引?,python,list,numpy,multidimensional-array,2d,Python,List,Numpy,Multidimensional Array,2d,我有一个2D列表。我想找到每行的最大值及其索引。 这是名单 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,
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.
然后,您可以使用zip函数将这两个列表一起迭代,并将输出存储在list of list中
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]]
np.max(q_表,轴=1)
?用于循环max
,argmax
,然后使用列堆栈result@QuangHoang这给了我一个最大值的列表。这也很好,但我也需要索引。@Ayon134argmax
,正如cs95建议的那样
[[2, 0.61], [1, 0.79], [3, 0.93], [2, 0.61], [3, 0.69]]