Re: Hi, friends. I wanna ask if there is a function which is able to take a list as argument and then return its top-k maximums?
- From: "Rhodri James" <rhodri@xxxxxxxxxxxxxxxxxxxx>
- Date: Thu, 22 Apr 2010 23:50:55 +0100
On Thu, 22 Apr 2010 15:23:29 +0100, D'Arcy J.M. Cain <darcy@xxxxxxxxx> wrote:
On Fri, 23 Apr 2010 00:07:18 +1000
Xavier Ho <contact@xxxxxxxxxxxx> wrote:
> print (sorted (l, reverse=True)[:k])
You don't really need to reverse sort there:
>>> numbers = [1, 4, 5, 3, 7, 8]
[5, 7, 8]
Now try returning the top two or four numbers.
[4, 5, 7, 8]sorted(numbers)[-4:]
or in general
That said, reverse sorting is probably clearer, and might be marginally faster, though frankly I can't be bothered to check that.
Rhodri James *-* Wildebeeste Herder to the Masses
- Prev by Date: Re: Calling multiple programs with subprocess
- Next by Date: csv.py sucks for Decimal
- Previous by thread: Re: Hi, friends. I wanna ask if there is a function which is able to take a list as argument and then return its top-k maximums?
- Next by thread: Accessing Twitter with Python (Python goes mainstream)