m ->我的矩阵
m = [[19, 17, 12], [6, 9, 3], [8, 11, 1], [18, 1, 12]]
最大->我已经找到了最大的数字
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
我该如何处理?
答案 0 :(得分:2)
从我的个人“备忘单”中,或根据“ HS-星云”的建议numpy docs:
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])
答案 1 :(得分:0)
您需要使用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
,则会得到** Index of 11(row,col): 2 1
。
答案 2 :(得分:0)
您不需要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])+')')
输出:
max at 0,0(19)
和
m = [[19, 17, 12], [20, 9, 3], [8, 11, 1], [18, 1, 12]]
max at 1,0(20)
答案 3 :(得分:0)
使用numpy
更简单。您可以使用以下代码在矩阵(数组)中找到最大值的坐标(xi,yi):
import numpy as np
m = np.array([[19, 17, 12], [6, 9, 3], [8, 11, 1], [18, 1, 12]])
i = np.unravel_index(np.argmax(m), m.shape)