[Tutor] manipulating list of lists

Brian van den Broek broek at cc.umanitoba.ca
Tue Oct 25 05:46:20 CEST 2005


John Fouhy said unto the world upon 2005-10-24 22:18:
> 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)]


And that would be the better suggestion I predicted :-)

I also should have pointed out that I wrote

 >>> noneless = [[x, y] for [x, y] in orig_list if not (x is None or y 
is None)]

to be fully explicit. Better in real code (I think) would be

 >>> noneless = [x for x in orig_list if not None in x]
 >>> noneless
[['c', 'b'], ['a', 'g'], ['e', 'f']]
 >>>


Best,

Brian vdB



More information about the Tutor mailing list