如何在Python中找到最大矩阵数的索引？

问题描述投票：2回答：4

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>", line 4, in <module>
print(m.index(c))
ValueError: 19 is not in list
``````

python python-3.x
4个回答
2

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

0

``````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])+')')
``````

`m = [[19, 17, 12], [20, 9, 3], [8, 11, 1], [18, 1, 12]]`

`max at 1,0(20)`

0

``````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)
``````

0

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