[Tutor] manipulating list of lists
John Fouhy
john at fouhy.net
Tue Oct 25 05:18:14 CEST 2005
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])
>>> arr
[('d', 1), ('e', 2), ('b', 3), ('a', 5), ('c', 7)]
--
John.
More information about the Tutor
mailing list