对点分隔数字列表进行排序,如软件版本

时间:2010-04-04 09:51:57

标签: python

我有一个包含版本字符串的列表,例如:

versions_list = ["1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"]

我想对它进行排序,结果会是这样的:

versions_list = ["1.0.0", "1.0.2", "1.0.12", "1.1.2", "1.3.3"]

数字的优先顺序显然应该是从左到右,它应该是降序。因此1.2.3出现在2.2.3之前2.2.2出现在2.2.3之前。

我如何在Python中执行此操作?

4 个答案:

答案 0 :(得分:109)

您还可以使用标准库的distutils.version模块:

from distutils.version import StrictVersion
versions = ["1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"]
versions.sort(key=StrictVersion)

给你:

['1.0.0', '1.0.2', '1.0.12', '1.1.2', '1.3.3']

它还可以处理带有预发布标记的版本,例如:

versions = ["1.1", "1.1b1", "1.1a1"]
versions.sort(key=StrictVersion)

给你:

["1.1a1", "1.1b1", "1.1"]

文档:https://github.com/python/cpython/blob/3.2/Lib/distutils/version.py#L101

答案 1 :(得分:75)

拆分每个版本字符串,将其作为整数列表进行比较:

versions_list.sort(key=lambda s: map(int, s.split('.')))

给你的清单:

['1.0.0', '1.0.2', '1.0.12', '1.1.2', '1.3.3']

在Python3 map中不再返回list,因此我们需要wrap it in a list call

versions_list.sort(key=lambda s: list(map(int, s.split('.'))))

此处映射的替代方法是list comprehension。有关列表推导的更多信息,请参阅this post

versions_list.sort(key=lambda s: [int(u) for u in s.split('.')])

答案 2 :(得分:13)

natsort建议"自然排序&#34 ;;这非常直观(在Python 3中)

from natsort import natsorted
versions = ["1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"]
natsorted(versions)

给出

['1.0.0', '1.0.2', '1.0.12', '1.1.2', '1.3.3']

但它也适用于版本号为

的完整软件包名称
versions = ['version-1.9', 'version-2.0', 'version-1.11', 'version-1.10']
natsorted(versions)

给出

['version-1.9', 'version-1.10', 'version-1.11', 'version-2.0']

答案 3 :(得分:1)

我也使用Python解决了这个问题,虽然我的版本做了一些额外的事情,这是我的代码:

def answer(l):
    list1 = [] # this is the list for the nested strings
    for x in l:
        list1.append(x.split("."))
    list2 = [] # this is the same list as list one except everything  is an integer in order for proper sorting
    for y in list1:
        y = map(int, y)
        list2.append(y)
    list3 = sorted(list2) #this is the sorted list of of list 2
    FinalList = [] # this is the list that converts everything back to the way it was
    for a in list3:
        a = '.'.join(str(z) for z in a)
        FinalList.append(a)
    return FinalList

对于版本,存在三件事;主要,次要和修订。它的作用是组织它,以便'1''1.0'之前到来'1.0.0'。此外,另外一个优点,不需要导入任何库,因为你没有它们,并且它适用于旧版本的Python,这个版本特别适用于2.7.6版本。无论如何,这里有几个例子:

Inputs:
    (string list) l = ["1.1.2", "1.0", "1.3.3", "1.0.12", "1.0.2"]
Output:
    (string list) ["1.0", "1.0.2", "1.0.12", "1.1.2", "1.3.3"]

Inputs:
    (string list) l = ["1.11", "2.0.0", "1.2", "2", "0.1", "1.2.1", "1.1.1", "2.0"]
Output:
    (string list) ["0.1", "1.1.1", "1.2", "1.2.1", "1.11", "2", "2.0", "2.0.0"]

如果您有任何疑问,请回答评论!!