Results 1 to 4 of 4

Thread: Sorting lists in python where 10 comes after 9.

  1. #1
    Join Date
    Jul 2005
    Location
    UC Irvine
    Beans
    342
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Sorting lists in python where 10 comes after 9.

    Hey everyone. I have a list in python like:

    Code:
    ['file-1', 'file-9', 'file-2', 'file-10']
    When I try and sort this list I get the sorting that you would get if you typed ls in a unix directory:

    Code:
    ['file-1', 'file-10', 'file-2', 'file-9']
    where 10 comes after 1 but before 2. I would like to sort this list such that 10 comes after 9 like:

    Code:
    ['file-1', 'file-2', 'file-9', 'file-10']
    Is there a simple way to do this with python? Thanks.

  2. #2
    Join Date
    Jun 2009
    Beans
    352

    Re: Sorting lists in python where 10 comes after 9.

    Crappy solution that works:

    Code:
    sorted(['file-1', 'file-9', 'file-2', 'file-10'], key=lambda s: int(s[5:]))
    http://wiki.python.org/moin/HowTo/Sorting <- go here for details.

    EDIT : Answer below is better
    Last edited by JDShu; February 10th, 2013 at 04:35 AM.

  3. #3
    Join Date
    Jul 2007
    Location
    Poland
    Beans
    4,499
    Distro
    Ubuntu 14.04 Trusty Tahr

    Re: Sorting lists in python where 10 comes after 9.

    there is a way, but not necessarily simple. You have to plug your own sorting rule into the stock sorting (define what to do with the value to get the sorting key).

    simple example of the concept where the values are sorted by 2nd part of the string cast to integer
    Code:
    >>> l = [ 'a-1', 'a-2', 'a-11' ]
    >>> sorted( l, key=lambda a: int(a.split("-")[1]) )
    ['a-1', 'a-2', 'a-11']
    more suitable solutions from google
    http://stackoverflow.com/questions/4...g-natural-sort

    if you process real files and are in control of their names, do yourself a favor and pad them with 0s to fixed width so even standard alphanumeric sorting returns correct order.
    if your question is answered, mark the thread as [SOLVED]. Thx.
    To post code or command output, use [code] tags.
    Check your bash script here // BashFAQ // BashPitfalls

  4. #4
    Join Date
    Jul 2005
    Location
    UC Irvine
    Beans
    342
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: Sorting lists in python where 10 comes after 9.

    Thanks a lot guys.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •