开发者

Sorting numbers in string format with Python [duplicate]

This question already has answers here: Sorting a list of dot-separated numbers, like software versions (6 answers) Closed 7 years ago.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜