How to find the max number(s) in a list with tied numbers

后端 未结 4 534
[愿得一人]
[愿得一人] 2020-12-06 06:07

So say I have a list like:

my_list = [12, 13, 51, 21, 22, 58, 45.1, 34.2, 56, 6, 58, 58] 

So the max number in this is obviously 58, but I

相关标签:
4条回答
  • 2020-12-06 06:38

    I tried to do the most Pythonic way as possible

    my_list = [12, 13, 51, 21, 22, 58, 45.1, 34.2, 56, 6, 58, 58] 
    max_indices = [i for i in range(len(my_list)) if my_list[i] == max(my_list)]
    

    Edit: Ashwini is right. max() needs to be outside the list, so...

    max_value = max(my_list)
    max_indices = [i for i in range(len(my_list)) if my_list[i] == max_value]
    
    0 讨论(0)
  • 2020-12-06 06:47

    Enumerate will help you to get the value and location

    maxx = max(my_list)
    for i,j in enumerate(my_list):
        if j == maxx:
            print i,j
    

    output

    5 58

    10 58

    11 58

    0 讨论(0)
  • 2020-12-06 06:48

    You can determine the maxval with max:

    maxval = max(my_list)
    

    Then get the indices using enumerate and a list comprehension:

    indices = [index for index, val in enumerate(my_list) if val == maxval]
    

    For your example, I get

    maxval == 58
    indices = [5, 10, 11]
    

    As per Keyser's suggestion, you could save iterating over the list twice (once to determine maxval, once to find matching indexes) by doing:

    maxval = None
    for index, val in enumerate(my_list):
        if maxval is None or val > maxval:
            indices = [index]
            maxval = val
        elif val == maxval:
            indices.append(index)
    
    0 讨论(0)
  • 2020-12-06 06:52

    Similar to enumerate and list comprehension, you can also use filter:

    maxval = max(my_list)
    indices = list(filter(lambda x: my_list[x]==maxval, list(range(len(my_list)))))
    
    0 讨论(0)
提交回复
热议问题