Thread: Sorting tuples

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Location
    Questioner's home
    Posts
    89
    Rep Power
    11

    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. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2004
    Posts
    84
    Rep Power
    11
    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
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    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

IMN logo majestic logo threadwatch logo seochat tools logo