8

I have a list that has some chapter numbers in string. When I sort the keys using keys function, it gives me wrong results.

keys = ['1.1', '1.2', '2.1', '10.1'] 
keys.sort() 
print keys

['1.1', '1.2', '10.1', '2.1']

How can I use the sort function to get

['1.1', '1.2', '2.1', '10.1']

What if the array has something like this?

['1.1.1', '1.2.1', '10.1', '2.1'] -> ['1.1.1','1.2.1','2.1','10.1']

1
  • 1
    Prosseek try this: keys.sort(key=float) , I just learn here Commented Jul 4, 2013 at 15:57

4 Answers 4

10
keys.sort(key=lambda x: [int(y) for y in x.split('.')])
Sign up to request clarification or add additional context in comments.

Comments

4
from distutils.version import StrictVersion
keys.sort(key=StrictVersion)

Since chapter numbers are a subset of version numbers, this covers your needs.

1 Comment

Worked create for me. However, I used LooseVersion from the same module instead because I sort versions from an external source.
2

This works:

keys.sort(key=lambda x: map(int, x.split('.')))

1 Comment

+1 This is a good answer for python2. In Python3 sorting maps no longer works, so you need to use list(map(...)) which is uglier than the list comprehension in my opinion.
1

Provide a custom key argument to sort or sorted.

From http://docs.python.org/library/functions.html#sorted:

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

1 Comment

>>> float('1.1.1') ... ValueError: invalid literal for float(): 1.1.1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.