如何在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
投票

从我个人的“备忘单”,或“HS-nebula”提出的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])

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)


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)

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

© www.soinside.com 2019 - 2024. All rights reserved.