How to find the 1st, 2nd, 3rd highest values ​​in a list in Python

I know how to find the 1st highest value, but I don’t know the others. Keep in mind, I need to print the 1st 1st 2nd and 3rd highest value position. Thank you and try to keep it simple, as I only coded 2 months. They can also be combined in rows.

def linearSearch(Fscore_list): pos_list = [] target = (max(Fscore_list)) for i in range(len(Fscore_list)): if Fscore_list[i] >= target: pos_list.append(i) return pos_list 
+5
source share
8 answers

This will print a list of the 3 highest elements, each of which has its own index:

 lst = [9,7,43,2,4,7,8,5,4] print( sorted( [(x,i) for (i,x) in enumerate(lst)], reverse=True )[:3] ) 

A little more complicated if the same value can appear several times (this will show the highest position for the value):

 lst = [9,7,43,2,4,7,8,5,4] ranks = sorted( [(x,i) for (i,x) in enumerate(lst)], reverse=True ) values = [] posns = [] for x,i in ranks: if x not in values: values.append( x ) posns.append( i ) if len(values) == 3: break print zip( values, posns ) 
+3
source

Use heapq.nlargest :

 >>> import heapq >>> [i ... for x, i ... in heapq.nlargest( ... 3, ... ((x, i) for i, x in enumerate((0,5,8,7,2,4,3,9,1))))] [7, 2, 3] 
+2
source

Add all the values ​​to the list in the set. This ensures that you will have each value only once.

Sorting a set.

Find the index of the top three values ​​in the set in the source list.

Make sense?

Edit

 thelist = [1, 45, 88, 1, 45, 88, 5, 2, 103, 103, 7, 8] theset = frozenset(thelist) theset = sorted(theset, reverse=True) print('1st = ' + str(theset[0]) + ' at ' + str(thelist.index(theset[0]))) print('2nd = ' + str(theset[1]) + ' at ' + str(thelist.index(theset[1]))) print('3rd = ' + str(theset[2]) + ' at ' + str(thelist.index(theset[2]))) 

Edit

You still haven’t told us how to deal with the “joint winners,” but looking at your answers to the other answers, I assume that this may be what you are trying to do, maybe? If this is not the result you want, please give us an example of the output you are hoping to get.

 thelist = [1, 45, 88, 1, 45, 88, 5, 2, 103, 103, 7, 8] theset = frozenset(thelist) theset = sorted(theset, reverse=True) thedict = {} for j in range(3): positions = [i for i, x in enumerate(thelist) if x == theset[j]] thedict[theset[j]] = positions print('1st = ' + str(theset[0]) + ' at ' + str(thedict.get(theset[0]))) print('2nd = ' + str(theset[1]) + ' at ' + str(thedict.get(theset[1]))) print('3rd = ' + str(theset[2]) + ' at ' + str(thedict.get(theset[2]))) 

Output

 1st = 103 at [8, 9] 2nd = 88 at [2, 5] 3rd = 45 at [1, 4] 

BTW: What if all the values ​​are the same (equal to the first) or for some other reason there is no third place? (or second place?). Do you need to protect yourself from this? If you do this, I am sure that you can design appropriate firewalls to add code.

+1
source

If the values ​​may appear in your list again, you can try this solution.

 def search(Fscore_list, num=3): l = Fscore_list res = dict([(v, []) for v in sorted(set(l), reverse=True)[:num]]) for index, val in enumerate(l): if val in res: res[val].append(index) return sorted(res.items(), key=lambda x: x[0], reverse=True) 

First, it will find num=3 the highest values ​​and create a dict with an empty list for indexes for it. Then it will go through the list and for each of the highest values ​​( val in res ) will save its indices. Then just return the sorted list of tuples, for example [(highest_1, [indexes ...]), ..] . eg.

 >>> l = [9, 7, 43, 2, 4, 7, 43, 8, 5, 8, 4] >>> print(search(l)) [(43, [2, 6]), (9, [0]), (8, [7, 9])] 

To print line items, do something like:

 >>> Fscore_list = [9, 7, 43, 2, 4, 7, 43, 8, 5, 8, 4, 43, 43, 43] >>> result = search(Fscore_list) >>> print("1st. %d on positions %s" % (result[0][0], result[0][1])) 1st. 43 on positions [2, 6, 11, 12, 13] >>> print("2nd. %d on positions %s" % (result[1][0], result[1][1])) 2nd. 9 on positions [0] >>> print("3rd. %d on positions %s" % (result[2][0], result[2][1])) 3rd. 8 on positions [7, 9] 
0
source

There is a complex O (n) algorithm, but the easiest way is to sort it, that is, O (n * log n), and then get the upper hand. The hardest part here is sorting the data while storing the index information.

 from operator import itemgetter def find_top_n_indices(data, top=3): indexed = enumerate(data) # create pairs [(0, v1), (1, v2)...] sorted_data = sorted(indexed, key=itemgetter(1), # sort pairs by value reversed=True) # in reversed order return [d[0] for d in sorted_data[:top]] # take first N indices data = [5, 3, 6, 3, 7, 8, 2, 7, 9, 1] print find_top_n_indices(data) # should be [8, 5, 4] 

Similarly, this can be done using heapq.nlargest() , but you still need to pack the original data into tuples and unpack it later.

0
source

For the list to be filtered and returned in descending order with duplicate removal, try using this function. You can pass in how many downstream values ​​you want to return as keyword arguments.

Also note that if the keyword argument (ordered_nums_to_return) is greater than the length of the list, it will return the entire list in descending order. if you need to create an exception, you can add a function check. If no arguments are passed, it will return the highest value, again you can change this behavior if you need to.

 list_of_nums = [2, 4, 23, 7, 4, 1] def find_highest_values(list_to_search, ordered_nums_to_return=None): if ordered_nums_to_return: return sorted(set(list_to_search), reverse=True)[0:ordered_nums_to_return] return [sorted(list_to_search, reverse=True)[0]] print find_highest_values(list_of_nums, ordered_nums_to_return=4) 
0
source

Start by sorting the list in descending order:

 my_list = [1, 2, 8, 4, 7, 6, 5, 3] sorted_list = sorted(my_list, reverse=True) print(sorted_list) 

Output:

 [8, 7, 6, 5, 4, 3, 2, 1] 

Then you can extract the index from the three largest elements (the first 3 elements of sorted_list ) as follows:

 index_of_highest = my_list.index(sorted_list[0]) index_of_second_highest = my_list.index(sorted_list[1]) index_of_third_highest = my_list.index(sorted_list[2]) 
-1
source

None always considered less than any number.

 >>> None<4 True >>> None>4 False 

Find the highest element and its index. Replace it with None . Find the new highest element and its index. This will be second in the original list. Replace it with None . Find the new highest item, which is actually the third.

Optional: restore found items in the list.

This is O (the number of the highest elements * the size of the list), so it does not scale well if your three grow, but now it is O (3n).

-1
source

All Articles