sorting a list of list

Discussion in 'Python' started by james_027, Nov 21, 2007.

  1. james_027

    james_027 Guest

    hi,

    are there available library or pythonic algorithm for sorting a list
    of list depending on the index of the list inside the list of my
    choice?

    d_list = [
    ['a', 1, 9],
    ['b', 2, 8],
    ['c', 3, 7],
    ['d', 4, 6],
    ['e', 5, 5],
    ]

    Thanks
    james
     
    james_027, Nov 21, 2007
    #1
    1. Advertisements

  2. james_027

    Tim Chase Guest

    are there available library or pythonic algorithm for sorting a list
    The built-in sorted() function and the sort() method on various
    collections take an optional "key=function" keyword paramater
    with which you can pass a function (lambdas are convenient) to
    extract the bit on which you want to compare:
    .... ['a', 1, 9],
    .... ['b', 2, 8],
    .... ['c', 3, 7],
    .... ['d', 4, 6],
    .... ['e', 5, 5],
    .... ]sorted(iterable, cmp=None, key=None, reverse=False) --> new
    sorted list
    [['a', 1, 9], ['b', 2, 8], ['c', 3, 7], ['d', 4, 6], ['e', 5, 5]]

    -tkc
     
    Tim Chase, Nov 21, 2007
    #2
    1. Advertisements

  3. Not to be too complicated, but there are functions that return a
    callable that is faster than a lambda.

    Then, instead of "lambda x: x[2]" use "operator.itemgetter(2)" and
    instead of "lambda x: x.foo" use "operator.attrgetter('foo')".
    --
     
    Matt Nordhoff, Nov 21, 2007
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.