Is there a more elegant way to do this?

Larry Whitley ldw at us.ibm.com
Wed Sep 13 14:22:54 EDT 2000


Here's the problem:

I have a list of counters that will have a wide variety of different values
in them.  At intervals while the program runs, I will print out the indexes
of the counters with the five largest counts.  The counters are in a list
identified below as self.counters.  Here's my inelegant way of doing it.

def runningReport(self): # a method of a larger class
    temp = [] # to make sure that temp is not just another reference to
self.counters
    temp = temp + self.counters # there are 100 individual counts in
self.counters
    temp.sort()
    temp.reverse() # now largest value is first
    temp2 = [] # for the result
    for i in range( 5 ):
        temp2.append( self.counters.index( temp[i] ) # find the index of the
next (largest) counter and store it in temp2
    print temp2

Surely there is a better way....

Larry





More information about the Python-list mailing list