Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Versions in Python

I'm trying to get it so that 1.7.0 comes after 1.7.0.rc0 but before 1.8.0, as it should if you were sorting versions. I thought the whole point of LooseVersion was that it handled the sorting and comparison of this kind of thing correctly.

>>> from distutils.version import LooseVersion
>>> versions = ["1.7.0", "1.7.0.rc0", "1.8.0"]
>>> lv = [LooseVersion(v) for v in versions]
>>> sorted(lv, reverse=True)
[LooseVersion ('1.8.0'), LooseVersion ('1.7.0.rc0'), LooseVersion ('1.7.0')]
like image 944
Tyler Brock Avatar asked Sep 04 '12 00:09

Tyler Brock


People also ask

What is sort () in Python?

Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically. Note: You cannot sort a list that contains BOTH string values AND numeric values.

How do you sort semantic versions?

If you find yourself having to sort using semantic version strings, (sorting a list of releases chronologically, say), we first need to split the string into its values and then compare each value. In this case we would sort by major release first, then minor, then finally by patch number.


1 Answers

>>> from distutils.version import LooseVersion
>>> versions = ["1.7.0", "1.7.0rc0", "1.11.0"]
>>> sorted(versions, key=LooseVersion)
['1.7.0', '1.7.0rc0', '1.11.0']

from the docs

Version numbering for anarchists and software realists. Implements the standard interface for version number classes as described above. A version number consists of a series of numbers, separated by either periods or strings of letters. When comparing version numbers, the numeric components will be compared numerically, and the alphabetic components lexically.
...
In fact, there is no such thing as an invalid version number under this scheme; the rules for comparison are simple and predictable, but may not always give the results you want (for some definition of "want").

so you see there is no smarts about treating "rc" specially

You can see how the version number is broken down like this

>>> LooseVersion('1.7.0rc0').version
[1, 7, 0, 'rc', 0]
like image 189
John La Rooy Avatar answered Oct 02 '22 05:10

John La Rooy