Prev: Calling multiple programs with subprocess
Next: question about an exciting gotcha for unittests (and elsewhere) ...
From: Rhodri James on 22 Apr 2010 18:50 On Thu, 22 Apr 2010 15:23:29 +0100, D'Arcy J.M. Cain <darcy(a)druid.net> wrote: > On Fri, 23 Apr 2010 00:07:18 +1000 > Xavier Ho <contact(a)xavierho.com> wrote: >> > print (sorted (l, reverse=True)[:k]) >> >> You don't really need to reverse sort there: > > True but... > >> >>> numbers = [1, 4, 5, 3, 7, 8] >> >>> sorted(numbers)[3:] >> [5, 7, 8] > > Now try returning the top two or four numbers. >>> sorted(numbers)[-2:] [7, 8] >>> sorted(numbers)[-4:] [4, 5, 7, 8] or in general >>> sorted(numbers)[-k:] 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 |