Version number comparison in Python

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

    Remove trailing .0 and .00 with regex, split and use cmp function which compares arrays correctly:

    def mycmp(v1,v2):
     c1=map(int,re.sub('(\.0+)+\Z','',v1).split('.'))
     c2=map(int,re.sub('(\.0+)+\Z','',v2).split('.'))
     return cmp(c1,c2)
    

    And, of course, you can convert it to a one-liner if you don't mind the long lines.

提交回复
热议问题