Is there a more elegant way to do this?
Aahz Maruch
aahz at panix.com
Wed Sep 13 14:55:14 EDT 2000
In article <8poglt$10fq$1 at news.rchland.ibm.com>,
Larry Whitley <ldw at us.ibm.com> wrote:
>
>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
This isn't much more elegent, but it's much more efficient:
def runningReport(self, numItems=5): # a method of a larger class
if numItems > len(self.counter):
numItems = len(self.counter)
numItems = -1 * abs(int(numItems)) # make sure numItems is negative int
temp = self.counters[:] #make copy of self.counters
temp.sort()
temp2 = temp[numItems:] #negative numItems pulls from end of list
temp2.reverse() #Change to descending order?
print temp2
--
--- Aahz (Copyright 2000 by aahz at pobox.com)
Androgynous poly kinky vanilla queer het <*> http://www.rahul.net/aahz/
Hugs and backrubs -- I break Rule 6
"I'm not aware of any public servant on Usenet, and thank God for that." --rra
More information about the Python-list
mailing list