tags:

views:

87

answers:

2

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 precendece 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?

+7  A: 

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']
Eli Bendersky
For the regular expression solution you would just replace the s with the expression that returns the group that you want. For example: lambda s: map(int, re.search(myre, s).groups[0].split('.'))
Andrew Cox
Thank you, worked like a charm
Zack
+10  A: 

You can also use distutils.version module of standard library:

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)

Gives you:

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

It can also handle versions with pre-release tags, for example:

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

Gives you:

["1.1a1", "1.1b1", "1.1"]
andreypopp
+1. Cool. I'd prefer this solution.
Eddy Pronk
Seems more pythonic then Eli's solution.
Vojtech R.