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

prosseek
  • 182,215
  • 215
  • 566
  • 871
  • 1
    Prosseek try this: `keys.sort(key=float)` , I just learn [here](http://stackoverflow.com/questions/17474211/how-to-sort-python-list-of-strings-of-numbers/17474264#17474264) – Grijesh Chauhan Jul 04 '13 at 15:57

4 Answers4

10
keys.sort(key=lambda x: [int(y) for y in x.split('.')])
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
4
from distutils.version import StrictVersion
keys.sort(key=StrictVersion)

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

tzot
  • 92,761
  • 29
  • 141
  • 204
  • 1
    Worked create for me. However, I used `LooseVersion` from the same module instead because I sort versions from an external source. – Martin Scharrer Oct 19 '11 at 17:01
2

This works:

keys.sort(key=lambda x: map(int, x.split('.')))
Wolph
  • 78,177
  • 11
  • 137
  • 148
  • +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. – John La Rooy Apr 08 '10 at 03:49
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).

harto
  • 89,823
  • 9
  • 47
  • 61