So I have a list that contains several list which all have three strings first, then one float number, like:
resultlist = [["1", "1", "a", 8.3931], ["1", "2", "b", 6.3231], ["2", "1", "c", 9.1931]]
How do I make a function that returns the maximum value (which here would be 9.1931)? I tried
def MaxValue():
max_value = max(resultlist)
return max_value
but that just gives me a list.
EDIT: Also, any way I could get the index for where the value comes from? Like, from which sublist?
Loop through your outer list and select the last element of each sublist:
It's also best if you keep all function related variables in-scope (pass the list as an argument and don't confuse the namespace by reusing variable names).
If you want the index too you can use
enumerate
withoperator.itemgetter
usingmap
:Which will return a tuple of the max with the index:
Or just a regular gen exp:
In perhaps a more functional than pythonic manner:
It begins by mapping each element of result list to the number value and then finds the max.
The intermediate array is:
Numpy helps with numerical nested lists. Try this:
max()
returns the list which first element is the maximum of all lists' first element, whilenp.max()
returns the highest value from all the nested lists.Output:
Are you trying to just get the maximum number from the floats (the last index in your list)? If so, here's a solution.