m -> Ma matrice
Traceback (most recent call last):
File "<pyshell#97>", line 4, in <module>
print(m.index(c))
ValueError: 19 is not in list
max -> J'ai déjà trouvé le plus grand nombre
for i in range(len(m)):
for c in m[i]:
if c==19:
print(m.index(c))
Maintenant, je ne trouve pas l'index
max = 19
J'ai eu une erreur p>
m = [[19, 17, 12], [6, 9, 3], [8, 11, 1], [18, 1, 12]]
Comment puis-je aborder cela?
4 Réponses :
Vous devez utiliser numpy . Voici un code fonctionnel. Avec numpy.array , vous pouvez faire de nombreux calculs à partir de celui-ci.
** Index of 19(row,col): 0 0
Le résultat sera:
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)
Et si vous utilisez test_num = 11 , vous obtiendrez ** Index of 11 (row, col): 2 1 .
Vous n'avez pas besoin de numpy, vous pouvez effectuer la recherche de max et rechercher l'index en même temps.
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])+')')
Résultat:
max à 0,0 (19)
et avec
m = [[19, 17, 12], [20, 9, 3], [8, 11, 1], [18, 1, 12]] code >
max à 1,0 (20)
À partir de ma "feuille de triche" personnelle, ou comme proposé par "HS-nebula", le 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])
Dans la documentation , vous pourriez simplement avoir idx = np.unravel_index (...); imprimer (mat [idx])
C'est beaucoup plus simple en utilisant numpy . vous pouvez utiliser ce qui suit pour trouver les coordonnées (xi, yi) de la valeur maximale dans la matrice (tableau):
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)
cest la valeur. Pas l'index (ce n'est pas comme javascript). Faites simplementprint (c)vous avez oublié l'indexation, m [i] .index (c)