pythonsortingalphanumeric

sort version nicely with letters and numbers


for some reason I cannot find this example I want to sort version numbers nicely. for example [v2,v10,v1] to [v1,v2,v10] I really only need the max but I can't find anything for that either.


Solution

  • Don't reinvent the .whl, you can use packaging.version which implements version parsing and ordering as specified in PEP 440.

    To sort versions:

    >>> from packaging.version import Version
    >>> data = ['v2', 'v10', 'v1', 'v2.1', 'v2.1.1']
    >>> sorted(data, key=Version)
    ['v1', 'v2', 'v2.1', 'v2.1.1', 'v10']
    

    To find the latest version:

    >>> max(data, key=Version)
    'v10'