Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find multiple max value items in a list [duplicate]

I'm trying to figure out how I can take a list of integers and return all the items in that list into another list as their max value, but with their index.

So I need to be able to do this without using enumeration, lambda, numpy, or anything of that sort. It has to be really basic methods for lists. Basically, things like append, max, etc. . . If for statements are fine too.

To clarify what I'm trying to do, say I have a list: [4, 34, 0, 0, 6, 34, 1] I want it to return [1, 5]

like image 872
user3324536 Avatar asked Feb 19 '14 22:02

user3324536


People also ask

How do you find the maximum number of repeated values in a list in Python?

Make a set of the list so that the duplicate elements are deleted. Then find the highest count of occurrences of each element in the set and thus, we find the maximum out of it.

How do you find the maximum number of occurrences in Python?

Given a list, the task is to find the number of occurrences of the largest element of the list. Method 1: The naive approach is to find the largest element present in the list using max(list) function, then iterating through the list using a for loop and find the frequency of the largest element in the list.

How do you find the top 3 values in Python?

If you want to get the indices of the three largest values, you can just slice the list. It also supports sorting from smallest to largest by using the parameter rev=False .


2 Answers

Simplest approach:

in [24]: a = [4, 34, 0, 0, 6, 34, 1]

In [25]: j=0

In [26]: M=[]

In [27]: m = max(a)

In [28]: for i in a:
    if i==m:
        M.append(j)
    j+=1
   ....:     

In [29]: M
Out[29]: [1, 5]

Using list-comprehension and enumerate, the above can be shortened to:

In [30]: [i for i, x in enumerate(a) if x == max(a)]
Out[30]: [1, 5]
like image 152
Fredrik Pihl Avatar answered Sep 21 '22 09:09

Fredrik Pihl


A "fully manual" approach, using none of those pesky standard library functions:

def get_max_indices(vals):
    maxval = None
    index = 0
    indices = []
    while True:
        try:
            val = vals[index]
        except IndexError:
            return indices
        else:
            if maxval is None or val > maxval:
                indices = [index]
                maxval = val
            elif val == maxval:
                indices.append(index)
            index = index + 1

What it loses in brevity, it gains in... not much.

like image 44
jonrsharpe Avatar answered Sep 21 '22 09:09

jonrsharpe