|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Get inside! Sample the range of functionality easily built with JMSL Library for Time Series Data Analysis, Heat Maps, Portfolio Optimization, Monte Carlo Simulation, Stock Price Charting and more. Download Now! |
|
#1
|
|||
|
|||
|
Sorting tuples
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? |
|
#2
|
|||
|
|||
|
it certainly is. here's a little example:
Code:
>>> 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[1] - y[1]) >>> l [(1, 1, 1), (1, 2, 1), (1, 3, 1), (1, 4, 1), (1, 5, 1), (1, 8, 1)] >>> 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 |
|
#3
|
|||
|
|||
|
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. Code:
>>> lst = [('abc', 321, 'car'), ('abb', 152, 'airplane'), ('bbb', 201, 'tank'), ('lcl', 200, 'ship')]
>>> decorated = [ (val[1], val) for val in lst]
>>> decorated.sort()
>>> sorted = [ val for (key,val) in decorated]
>>> sorted
[('abb', 152, 'airplane'), ('lcl', 200, 'ship'), ('bbb', 201, 'tank'), ('abc', 321, 'car')]
>>>
This is also sometimes known as a Schwartzian Transform, after the originator of the perl version. Dave - The Developers' Coach |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > Sorting tuples |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|