[英]How do I find the index of the greatest number of a matrix in 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
我該如何解決這個問題?
從我個人的“備忘單”或“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])
您需要使用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
。
你不需要 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)
使用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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.