本文介绍了对以点分隔的数字列表进行排序,例如软件版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list containing version strings, such as things:

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

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

I would like to sort it, so the result would be something like this:

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

数字的优先顺序显然应该是从左到右,并且应该是降序.所以 1.2.32.2.3 之前,2.2.22.2.3 之前.

The order of precedence for the digits should obviously be from left to right, and it should be descending. So 1.2.3 comes before 2.2.3 and 2.2.2 comes before 2.2.3.

如何在 Python 中执行此操作?

How do I do this in Python?

推荐答案

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

Split each version string to compare it as a list of integers:

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,所以我们需要将其包装在 list 调用中.

In Python3 map no longer returns a list, So we need to wrap it in a list call.

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

此处映射的替代方法是列表理解.有关列表推导式的更多信息,请参阅这篇文章.

The alternative to map here is a list comprehension. See this post for more on list comprehensions.

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

这篇关于对以点分隔的数字列表进行排序,例如软件版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 07:18