Version number comparison in Python

后端 未结 17 2067
小蘑菇
小蘑菇 2020-11-27 10:32

I want to write a cmp-like function which compares two version numbers and returns -1, 0, or 1 based on their compared va

17条回答
  •  温柔的废话
    2020-11-27 11:39

    How about using Python's distutils.version.StrictVersion?

    >>> from distutils.version import StrictVersion
    >>> StrictVersion('10.4.10') > StrictVersion('10.4.9')
    True
    

    So for your cmp function:

    >>> cmp = lambda x, y: StrictVersion(x).__cmp__(y)
    >>> cmp("10.4.10", "10.4.11")
    -1
    

    If you want to compare version numbers that are more complex distutils.version.LooseVersion will be more useful, however be sure to only compare the same types.

    >>> from distutils.version import LooseVersion, StrictVersion
    >>> LooseVersion('1.4c3') > LooseVersion('1.3')
    True
    >>> LooseVersion('1.4c3') > StrictVersion('1.3')  # different types
    False
    

    LooseVersion isn't the most intelligent tool, and can easily be tricked:

    >>> LooseVersion('1.4') > LooseVersion('1.4-rc1')
    False
    

    To have success with this breed, you'll need to step outside the standard library and use setuptools's parsing utility parse_version.

    >>> from pkg_resources import parse_version
    >>> parse_version('1.4') > parse_version('1.4-rc2')
    True
    

    So depending on your specific use-case, you'll need to decide whether the builtin distutils tools are enough, or if it's warranted to add as a dependency setuptools.

提交回复
热议问题