sort the list

Peter Otten __peter__ at web.de
Wed Nov 23 04:45:36 EST 2005


bonono at gmail.com wrote:

> 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.

"Stability" means items with the same key preserve their relative position.
In the original list of the example [4, 1] and [4, 2] both have the same
key. Therefore [4, 1] should stay before [4, 2], so the second is the
"right" answer.

The practical advantage is that if e. g. you sort items first by color and
then by size, items of the same size will appear sorted by color. In
particular, sorting a list by the same key a second time does not change
the list.

Peter




More information about the Python-list mailing list