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"]
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
.
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('.')))
Gives, for your list:
['1.0.0', '1.0.2', '1.0.12', '1.1.2', '1.3.3']
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('.')])