Version number comparison in Python

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

    This is a little more compact than your suggestion. Rather than filling the shorter version with zeros, I'm removing trailing zeros from the version lists after splitting.

    def normalize_version(v):
        parts = [int(x) for x in v.split(".")]
        while parts[-1] == 0:
            parts.pop()
        return parts
    
    def mycmp(v1, v2):
        return cmp(normalize_version(v1), normalize_version(v2))
    

提交回复
热议问题