Version number comparison in Python

后端 未结 17 2066
小蘑菇
小蘑菇 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:30

    Lists are comparable in Python, so if someone converts the strings representing the numbers into integers, the basic Python comparison can be used with success.

    I needed to extend this approach a bit because I use Python3x where the cmp function does not exist any more. I had to emulate cmp(a,b) with (a > b) - (a < b). And, version numbers are not that clean at all, and can contain all kind of other alphanumeric characters. There are cases when the function can't tell the order so it returns False (see the first example).

    So I'm posting this even if the question is old and answered already, because it may save a few minutes in someone's life.

    import re
    
    def _preprocess(v, separator, ignorecase):
        if ignorecase: v = v.lower()
        return [int(x) if x.isdigit() else [int(y) if y.isdigit() else y for y in re.findall("\d+|[a-zA-Z]+", x)] for x in v.split(separator)]
    
    def compare(a, b, separator = '.', ignorecase = True):
        a = _preprocess(a, separator, ignorecase)
        b = _preprocess(b, separator, ignorecase)
        try:
            return (a > b) - (a < b)
        except:
            return False
    
    print(compare('1.0', 'beta13'))    
    print(compare('1.1.2', '1.1.2'))
    print(compare('1.2.2', '1.1.2'))
    print(compare('1.1.beta1', '1.1.beta2'))
    

提交回复
热议问题