如何在Python中找到矩阵最大数的索引?
m->我的矩阵如何在Python中找到矩阵最大数的索引?,python,python-3.x,Python,Python 3.x,m->我的矩阵 m = [[19, 17, 12], [6, 9, 3], [8, 11, 1], [18, 1, 12]] max->我已经找到了最大的数字 max = 19 现在我找不到索引了 for i in range(len(m)): for c in m[i]: if c==19: print(m.index(c)) 我有个错误 Traceback (most recent call last): File "<pyshell#97>
m = [[19, 17, 12], [6, 9, 3], [8, 11, 1], [18, 1, 12]]
max->我已经找到了最大的数字
max = 19
现在我找不到索引了
for i in range(len(m)):
for c in m[i]:
if c==19:
print(m.index(c))
我有个错误
Traceback (most recent call last):
File "<pyshell#97>", line 4, in <module>
print(m.index(c))
ValueError: 19 is not in list
回溯(最近一次呼叫最后一次):
文件“”,第4行,在
印刷品(m.index(c))
ValueError:19不在列表中
我怎样才能做到这一点 您需要使用
numpy
。这是一个工作代码。使用numpy.array
,您可以从中进行许多计算
import numpy as np
mar = np.array([[19, 17, 12], [6, 9, 3], [8, 11, 1], [18, 1, 12]])
# also OK with
# mar = [[19, 17, 12], [6, 9, 3], [8, 11, 1], [18, 1, 12]]
test_num = 19 # max(mar.flatten()) --> 19
for irow, row in enumerate(mar):
#print(irow, row)
for icol, col in enumerate(row):
#print(icol, col)
if col==test_num:
print("** Index of {}(row,col): ".format(test_num), irow, icol)
输出将是:
** Index of 19(row,col): 0 0
如果您使用
test_num=11
,您将得到**索引11(行,列):2 1
您不需要numpy,您可以同时搜索max和索引
m = [[19, 17, 12], [6, 9, 3], [8, 11, 1], [18, 1, 12]]
max_index_row = 0
max_index_col = 0
for i in range(len(m)):
for ii in range(len(m[i])):
if m[i][ii] > m[max_index_row][max_index_col]:
max_index_row = i
max_index_col = ii
print('max at '+str(max_index_row)+','+str(max_index_col)+'('+str(m[max_index_row][max_index_col])+')')
输出:
最大值为0,0(19)
和
m=[[19,17,12],[20,9,3],[8,11,1],[18,1,12]。
最大值为1,0(20)
来自我个人的“备忘单”,或根据“HS星云”的建议:
使用
numpy
,这会更简单。您可以使用以下方法查找矩阵(数组)中最大值的坐标(xi,yi):
将numpy导入为np
m=np.数组([[19,17,12],[6,9,3],[8,11,1],[18,1,12])
i=np.Unlavel_指数(np.argmax(m),m.shape)
c
是值。不是索引(它不像javascript)。只需打印(c)你忘记了索引,m[i]。从中的索引(c)你可以得到idx=np。解开索引(…);打印(mat[idx])
import numpy as np
mat = np.array([[1.3,3.4,0.1],[4.0,3.2,4.5]])
i, j = np.unravel_index(mat.argmax(), mat.shape)
print(mat[i][j])
# or the equivalent:
idx = np.unravel_index(mat.argmax(), mat.shape)
print(mat[idx])