March 26th, 2004, 12:06 AM
Lets say I have a list containing tuples like this : [('abc', 321, 'car'), ('abb', 152, 'airplane'), ('bbb', 201, 'tank'), ('lcl', 200, 'ship')]
I'd like to sort the tuples by the second element in the tuples - the numbers, izzit possible?
What can change the nature of a man?
March 26th, 2004, 01:36 AM
it certainly is. here's a little example:
applying that to your list of tuples should be easy from there. I believe there is a nice little doc on sorting objects on the Python site. try the "Howto texts" section at python.org/doc
>>> l = [(1, 8, 1), (1, 1, 1), (1, 5, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1)]
>>> l.sort(lambda x, y: x - y)
[(1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (1, 5, 1), (1, 8, 1)]
March 26th, 2004, 03:01 AM
You can pass a comparision function to list.sort(), as rebbit pointed out. However as this involve calling the fuction for every comparison it can seriously slow down sorting of large lists.
An alternative and faster way is to use the Decorate-Sort-Undecorate, or DSU, pattern. To do this, transform the list into a list of tuples with the value to be sorted on as the first element, sort the list, then transform it back. This can easily be done with list substitutions. e.g.
This is also sometimes known as a Schwartzian Transform, after the originator of the perl version.
>>> lst = [('abc', 321, 'car'), ('abb', 152, 'airplane'), ('bbb', 201, 'tank'), ('lcl', 200, 'ship')]
>>> decorated = [ (val, val) for val in lst]
>>> sorted = [ val for (key,val) in decorated]
[('abb', 152, 'airplane'), ('lcl', 200, 'ship'), ('bbb', 201, 'tank'), ('abc', 321, 'car')]
Dave - The Developers' Coach