Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get max value from a list with lists?

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?

like image 475
FeatherMarauder Avatar asked Oct 21 '15 21:10

FeatherMarauder


3 Answers

Loop through your outer list and select the last element of each sublist:

def max_value(inputlist):
    return max([sublist[-1] for sublist in inputlist])

print max_value(resultlist)
# 9.1931

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).

like image 117
wflynny Avatar answered Oct 06 '22 07:10

wflynny


In perhaps a more functional than pythonic manner:

>>> max(map(lambda x: x[3], resultlist))
9.1931

It begins by mapping each element of result list to the number value and then finds the max.

The intermediate array is:

>>> map(lambda x: x[3], resultlist)
[8.3931000000000004, 6.3231000000000002, 9.1930999999999994]
like image 28
Almog Avatar answered Oct 06 '22 07:10

Almog


Numpy helps with numerical nested lists. Try this:

resultlist = [[3, 2, 4, 4], [1, 6, 7, -6], [5, 4, 3, 2]]
max(resultlist)  # yields [5, 4, 3, 2] because 5 is the max in: 3, 1, 5
np.max(resultlist)  # yields 7 because it's the absolute max

max() returns the list which first element is the maximum of all lists' first element, while np.max() returns the highest value from all the nested lists.

like image 27
Guillermo Luijk Avatar answered Oct 06 '22 08:10

Guillermo Luijk