【问题标题】:How to sort numeric strings with 2 decimal points in python如何在python中对带有2个小数点的数字字符串进行排序
【发布时间】:2022-11-14 19:35:31
【问题描述】:

我在 linux 中有一些目录,其版本为目录名称:

1.1.0  1.10.0  1.5.0  1.7.0  1.8.0  1.8.1  1.9.1  1.9.2

我想从最低版本到最高版本对上述目录进行排序 当我尝试在 python 中使用 .sort 时,我最终低于

['1.1.0', '1.10.0', '1.5.0', '1.7.0', '1.8.0', '1.8.1', '1.9.1']

这实际上是不正确的,1.10.0 版本是所有版本中最大的,应该位于最后一个索引中,有没有办法使用 python 来处理这些事情。

提前致谢

【问题讨论】:

标签: python python-3.x list sorting


【解决方案1】:

由于您的版本是字符串数据类型。我们必须在每个点之后拆分。

v_list = ['1.1.0','1.10.0','1.5.0','1.7.0','1.8.0','1.8.1','1.9.1','1.9.2']
v_list.sort(key=lambda x: list(map(int, x.split('.'))))

或者你也可以试试这个:

v_list = ['1.1.0','1.10.0','1.5.0','1.7.0','1.8.0','1.8.1','1.9.1','1.9.2']
v_list.sort(key=lambda x: [int(y) for y in x.split('.')])

【讨论】:

    猜你喜欢
    • 2021-07-23
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    相关资源
    最近更新 更多