tags:

views:

73

answers:

4

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']

+4  A: 
keys.sort(key=lambda x: [int(y) for y in x.split('.')])
Ignacio Vazquez-Abrams
+2  A: 

This works:

keys.sort(key=lambda x: map(int, x.split('.')))
WoLpH
+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.
gnibbler
A: 

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).

harto
`>>> float('1.1.1')` ... `ValueError: invalid literal for float(): 1.1.1`
Ignacio Vazquez-Abrams
dang. Upvoted your answer
harto
+1  A: 
from distutils.version import StrictVersion
keys.sort(key=StrictVersion)

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

ΤΖΩΤΖΙΟΥ