A more pythonic way to find the first two largest values ​​in a list in python

These days I am developing some algorithms in python, but finding the first two largest values ​​in python is too ugly and inefficient.

How to implement it in an effective or Putin way?

+6
source share
3 answers

I found this to be consistently faster (about 2x for a list of 1,000,000 items) than heapq.nlargest :

 def two_largest(sequence): first = second = 0 for item in sequence: if item > second: if item > first: first, second = item, first else: second = item return first, second 

(function modified at the suggestion of MatthieuW)

Here are the results of my testing ( timeit executed forever, so I used time.time() ):

 >>> from random import shuffle >>> from time import time >>> seq = range(1000000) >>> shuffle(seq) >>> def time_it(func, *args, **kwargs): ... t0 = time() ... func(*args, **kwargs) ... return time() - t0 ... >>> #here I define the above function, two_largest(). >>> from heapq import nlargest >>> time_it(nlargest, 2, seq) 0.258958101273 >>> time_it(two_largest, seq) 0.145977973938 
+5
source

In most cases, Pythonic uses nlargest :

 import heapq values = heapq.nlargest(2, my_list) 
+16
source
 mylist = [100 , 2000 , 1 , 5] mylist.sort() biggest = mylist[-2:] 
+1
source

Source: https://habr.com/ru/post/917759/


All Articles