使用Python以字符串格式对数字进行排序 [英] Sorting numbers in string format with Python
本文介绍了使用Python以字符串格式对数字进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表,其中包含一些字符串中的章节编号. 当我使用按键功能对按键进行排序时,会给我错误的结果.
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']
如何使用sort函数获取
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('.')])
这篇关于使用Python以字符串格式对数字进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文