[Tutor] manipulating list of lists

Kent Johnson kent37 at tds.net
Tue Oct 25 11:58:34 CEST 2005


John Fouhy wrote:
> On 25/10/05, Brian van den Broek <broek at cc.umanitoba.ca> wrote:
> 
>>To sort by the second item, try
>>
>> >>> def sort_by_second(sequence):
>>        decorated = [(x[1], x) for x in sequence]
>>        decorated.sort()
>>        return [x[1] for x in decorated]
> 
> 
> With python2.4, you can use the key= argument to sort.
> 
> eg:
> 
>>>>arr = [('a', 5), ('b', 3), ('c', 7), ('d', 1), ('e', 2)]
>>>>arr.sort(key=lambda x: x[1])

and you can use operator.itemgetter() instead of a lambda - it is intended for this usage:
 >>> import operator
 >>> arr = [('a', 5), ('b', 3), ('c', 7), ('d', 1), ('e', 2)]
 >>> arr.sort(key=operator.itemgetter(1))
 >>> arr
[('d', 1), ('e', 2), ('b', 3), ('a', 5), ('c', 7)]

Kent

-- 
http://www.kentsjohnson.com



More information about the Tutor mailing list