具体排序由点分隔的数字列表 [英] Specific sort a list of numbers separated by dots
本文介绍了具体排序由点分隔的数字列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表:
L = ['1.1.1.', '1.1.10.', '1.1.11.', '1.1.12.', '1.1.13.', '1.1.2.', '1.1.3.', '1.1.4.']
我想按以下顺序对其进行排序:
I want to sort it in next order:
1.1.1.
1.1.2.
1.1.3.
1.1.4.
1.1.10.
1.1.11.
1.1.12.
1.1.13.
以下方法不会产生结果:
The following method does not produce a result:
L.sort(key=lambda s: int(re.search(r'.(\d+)',s).group(1)))
推荐答案
只需获取最后一部分,将其转换为int并将其作为比较的键即可返回
Just get the last part, convert that to an int and return it as the key for comparison
print(sorted(L, key=lambda x: int(x.split(".")[2])))
如果您想考虑所有部分,则可以这样做
If you want all the parts to be considered, you can do like this
print(sorted(L, key=lambda x: [int(i) for i in x.rstrip(".").split(".")]))
它将删除字符串末尾的.
,根据.
对其进行拆分,然后将其每个部分转换为int
.返回的列表将用于比较.
It removes .
at the end of the strings, splits them based on .
and then converts each and every part of it to an int
. The returned list will be used for comparison.
您可以通过这里
输出
['1.1.1.','1.1.2.','1.1.3.','1.1.4.','1.1.10.','1.1.11.','1.1.12.','1.1.13.']
这篇关于具体排序由点分隔的数字列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文