pythonlistfunctionpython-2.7max

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?


Solution

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