首页 > 解决方案 > 如何在 Python 中找到最大矩阵数的索引?

问题描述

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

我该如何处理?

标签: pythonpython-3.x

解决方案


从我个人的“备忘单”或“HS-nebula”建议的numpy 文档中:

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

推荐阅读