Sorting numbers in string format with Python [duplicate]
I have a list that has some c开发者_运维百科hapter 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']
keys.sort(key=lambda x: [int(y) for y in x.split('.')])
from distutils.version import StrictVersion
keys.sort(key=StrictVersion)
Since chapter numbers are a subset of version numbers, this covers your needs.
This works:
keys.sort(key=lambda x: map(int, x.split('.')))
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).
精彩评论