简体   繁体   中英

How can i get index of all the greatest elements in a nested list or matrix?

Below code is a possible solution to my problem but I am interested in doing this without numpy or any other python lib .

Input [[20, 1], [20, 7], [1, 9]]

Expected Output [(0, 0), (1, 0)]

import numpy as np

matrix = [[20, 1], [20, 7], [1, 9]]

arr2D = np.array(matrix)
result = np.where(arr2D == np.amax(arr2D))
listOfCordinates = list(zip(result[0], result[1]))
print(listOfCordinates) 

Thanks in Advance

This might not be the most efficient solution but helps

matrix = [[20, 1], [20, 7], [1, 9]]
xIndex = []
yIndex = []
maxValues = []
cord = []
finalCord = []
finalMaxIndex = []

for i in range(len(matrix)):

    xIndex.append(i)
    maxSublist = max(matrix[i])
    yIndex.append(matrix[i].index(maxSublist))

for i, j in zip(xIndex, yIndex):

    cord.append((i,j))
    maxValues.append(matrix[i][j])
    maxValue = max(maxValues)

for i in range(len(maxValues)):

    if maxValue == maxValues[i]:
        finalMaxIndex.append(i)
    else:
        pass

for i in finalMaxIndex:
    finalCord.append(cord[i])

print('Index of multiple greatest elements in nested list or matrix:', finalCord)
matrix = [[20, 1], [20, 7], [1, 9]]
output = [(0, 0), (1, 0)]

This here should work:

matrix = [[20, 1], [20, 7], [1, 9]]

max_n = matrix[0][0]
result = []
for row in range(len(matrix)):
    for col in range(len(matrix[0])):
        if matrix[row][col] == max_n:
            result.append((row, col))
        elif matrix[row][col] > max_n:
            max_n = matrix[row][col]
            result = [(row, col)]

print(result)

Find the max value of the list of lists first and then find the position of the elements whoe value is equal to the max value using a list comprehension

>>> lst = [[20, 1], [20, 7], [1, 9]]
>>> m = max(e for sub_lst in lst for e in sub_lst)
>>> [(i, j) for i,sub_lst in enumerate(lst) for j,e in enumerate(sub_lst) if e==m]
[(0, 0), (1, 0)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM