sort the list

bonono at gmail.com bonono at gmail.com
Wed Nov 23 04:22:53 EST 2005


Duncan Booth wrote:
> e.g. it is stable when you reverse the order:
>
> >>> lst = [[4,1],[4,2],[9,3],[5,4],[2,5]]
> >>> list(reversed([ x[-1] for x in sorted([ (x[0],x) for x in lst ]) ]))
> [[9, 3], [5, 4], [4, 2], [4, 1], [2, 5]]
> >>> l1 = list(lst)
> >>> l1.sort(key=operator.itemgetter(0), reverse=True)
> >>> l1
> [[9, 3], [5, 4], [4, 1], [4, 2], [2, 5]]
>
Just curious, which one is supposed to be the right answer ? and why
the second one is preferable over the first one(if both is right,
assume we only care about x[0]).

Of course, there is no reason to DIY when the built-in can do the job.




More information about the Python-list mailing list