Reputation: 1505
I have this list:
dCF3v=[[(1.90689635276794, -44704.76171875)],
[(1.90689635276794, -44705.76171875)],
[(1.90689635276794, -44706.76171875)],
[(1.90689635276794, -44707.76171875)]
]
I'd like to know the index of the row where the maximum value is. In the example above: row index 3.
I already have a code for finding the maximum value:
CF3a = (abs(x[0][1]) for x in dCF3v)
CF3 = max(CF3a)
If possible I'd like to adapt this code and not have to do the classic for and if loops
.
Upvotes: 0
Views: 79
Reputation: 107608
You can use enumerate
to keep the indices and the key
argument for max
to look for the right value:
dCF3v=[[(1.90689635276794, -44704.76171875)],
[(1.90689635276794, -44705.76171875)],
[(1.90689635276794, -44706.76171875)],
[(1.90689635276794, -44707.76171875)]
]
CF3a = (abs(x[0][1]) for x in dCF3v)
index, value = max(enumerate(CF3a), key=lambda (index, value): value)
print index,value
Upvotes: 2
Reputation: 213
Since your data appears to numerical in nature I would strongly recommend using the numpy module as it is designed in part to do what you're asking.
You can convert your data to a numpy array
import numpy as np
data = np.array(dCF3v)
and then use np.argmax
to find the index of the largest value
idx = np.argmax(data)
This gives you an index into the flattened array. If you know the shape of your array this flattened index is easily converted into a row number using modular arithmetic. You can get the number of rows and columns like this
rows,cols = data.shape
and then the row number with modular division
maxRow = idx%cols
numpy also has a function called unravel_index
which does the modular arithmetic for you,
row, col = np.unravel_index(idx, data.shape)
Upvotes: 1