python - Retrieve the two highest item from a list containing 100,000 integers -
how can retrieve 2 highest item list containing 100,000 integers without having sort entire list first?
in python, use heapq.nlargest
. flexible approach in case ever want handle more top 2 elements.
here's example.
>>> import heapq >>> import random >>> x = range(100000) >>> random.shuffle(x) >>> heapq.nlargest(2, x) [99999, 99998]
documentation: http://docs.python.org/library/heapq.html#heapq.nlargest
Comments
Post a Comment