Get max value from a list with lists?

前端 未结 7 508
南笙
南笙 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:18

    Here is an answer just in case you get a list of list where the number is not always on the 3rd position:

    from itertools import chain
    max(filter(lambda x: isinstance(x, (int, long, float)), chain.from_iterable(resultlist)))
    

    What is going on? itertools.chain flattens the list of lists, the filter then selects all the numeric values of which the maximal value is then determined using the max function. Advantage here is that it also works for arbitrary lists of lists where the numeric value can be found anywhere in the list.

    For your example:

    resultlist = [['1', '1', 'a', 8.3931], ['1', '2', 'b', 6.3231], ['2', '1', 'c', 9.1931]]
    max(filter(lambda x: isinstance(x, (int, long, float)), chain.from_iterable(resultlist))) 
    #prints 9.1931
    

    One more general example:

    myList = [[23, 34, 'a'],['b'],['t', 100]]
    max(filter(lambda x: isinstance(x, (int, long, float)), chain.from_iterable(myList)))
    #prints 100
    

    EDIT:

    If you also want to get the index of the maximal value, you can do the following (using @Padraic Cunningham approach):

    from itertools import chain
    import operator
    resultlist = [['1', '1', 'a', 8.3931], ['1', '2', 'b', 6.3231], ['2', '1', 'c', 9.1931]]
    l = filter(lambda x: isinstance(x, (int, long, float)), chain.from_iterable(resultlist))
    # l: [8.3931, 6.3231, 9.1931]
    max(enumerate(l), key = operator.itemgetter(1))
    #(2, 9.1931)
    

    This approach assumes that there is exactly one numeric value per list!

    One more example using a list where the numeric value is on an arbitrary position:

    from itertools import chain
    import operator
    myList = [[23, '34', 'a'],['b', 1000],['t', 'xyz', 100]]
    l=filter(lambda x: isinstance(x, (int, long, float)), chain.from_iterable(myList))
    max(enumerate(l), key = operator.itemgetter(1))
    #prints (1, 1000)
    
    0 讨论(0)
提交回复
热议问题