[Tutor] Getting the highest numbers from a list

Jesse W jessw@loop.com
Mon, 27 Aug 2001 12:20:34 -0700


David L. Lerner wrote:
> Is there a simple way to get the _n_ highest numbers from an unordered
> list?
Here is one way:

import random,operator #random to make the lists, operator to sum l2.

l1=[ random.randint(0, 200) for x in range(20) ] 
l2=[ random.randint(0, 200) for x in range(20) ]
#change the range to make shorter or longer lists, change the args to randint
#to make more or less varying lists.

def highest(list, num):
    """Return a list of the num highest items in list."""
    list.sort()
    tmp=list[-num:]
    tmp.reverse()
    return tmp

print highest(l1, 5), reduce(operator.add, highest(l2, 5)) 
#now, generate the high lists, and use reduce(operator.add) to sum the
#second list.
#Credit for the operator.add trick goes to Ignacio Vazquez-Abrams.

	Hope you like it,
		Jesse W