Home > OS >  Python: Iterate through list of list and print the max value and index
Python: Iterate through list of list and print the max value and index

Time:08-25

I am trying to iterate through list of list to find out the max value in each sublist along with the index.

data =tensor([[0.78,0.98,0.55,0.23],[0.82,0.45,0.56,0.33],[0.65,0.92,0.51,0.21]])

I need the output as value=0.98,index=(0,1), value=0.82,index=(1,0),value=0.92,index=(2,1)

CodePudding user response:

Try this:

data =[[0.78,0.98,0.55,0.23],[0.82,0.45,0.56,0.33],[0.65,0.92,0.51,0.21]]
for list in data:
    print ('Value=',max(list), ' Index = (', data.index(list), ',', list.index(max(list)), ')')

Value= 0.98  Index = ( 0 , 1 )
Value= 0.82  Index = ( 1 , 0 )
Value= 0.92  Index = ( 2 , 1 )

CodePudding user response:

you can find the maximum value of a list by 'max' and find the index value of that maximum value

data = [[0.78, 0.98, 0.55, 0.23], [0.82, 0.45, 0.56, 0.33], [0.65, 0.92, 0.51, 0.21]]

for ind, lst in enumerate(data):
    maxi_num = max(lst)
    index_val = lst.index(maxi_num)
    print(f'Value = {maxi_num},index = ({ind},{index_val})')

CodePudding user response:

Assuming a numpy array or similar:

import numpy as np

data = np.array([[0.78,0.98,0.55,0.23],
                   [0.82,0.45,0.56,0.33],
                   [0.65,0.92,0.51,0.21]])

col = np.argmax(data, axis=1)
# array([1, 0, 1])

row = np.arange(len(data))
# array([0, 1, 2])

data[row, col]
# array([0.98, 0.82, 0.92])
  • Related