Get max value from a list with lists?

前端 未结 7 507
南笙
南笙 2020-12-09 11:32

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], [\         


        
相关标签:
7条回答
  • 2020-12-09 12:00
    resultlist = [["1", "1", "a", 8.3931], ["1", "2", "b", 6.3231], ["2", "1", "c", 9.1931]]
    print(max(map(lambda x: x[-1],resultlist)))
    

    Output:

    9.1931
    
    0 讨论(0)
  • 2020-12-09 12:03

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

    0 讨论(0)
  • 2020-12-09 12:04

    If you want the index too you can use enumerate with operator.itemgetter using map:

    from operator import itemgetter
    def max_val(l, i):
        return max(enumerate(map(itemgetter(i), l)),key=itemgetter(1)))
    

    Which will return a tuple of the max with the index:

    In [7]: resultlist = [["1", "1", "a", 8.3931], ["1", "2", "b", 6.3231], ["2", "1", "c", 9.1931]]
    
    In [8]: max_val(resultlist, -1)
    Out[8]: (2, 9.1931)
    

    Or just a regular gen exp:

    from operator import itemgetter
    def max_val(l, i):
        return max(enumerate(sub[i] for sub in l), key=itemgetter(1))
    
    0 讨论(0)
  • 2020-12-09 12:05

    Are you trying to just get the maximum number from the floats (the last index in your list)? If so, here's a solution.

    last_indices = [x[3] for x in resultlist]
    return max(last_indices)
    
    0 讨论(0)
  • 2020-12-09 12:06

    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.

    0 讨论(0)
  • 2020-12-09 12:10

    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]
    
    0 讨论(0)
提交回复
热议问题