compare two python strings that contain numbers

前端 未结 5 1518
礼貌的吻别
礼貌的吻别 2020-12-19 11:29

UPDATE: I should have specified this sooner, but not all of the names are simply floats. For example, some of them are \"prefixed\" with \"YT\". So for example\" YT1.1. so,

5条回答
  •  情话喂你
    2020-12-19 12:27

    Convert the names to tuples of integers and compare the tuples:

    def splittedname(s):
        return tuple(int(x) for x in s.split('.'))
    
    splittedname(s1) > splittedname(s2)
    

    Update: Since your names apparently can contain other characters than digits, you'll need to check for ValueError and leave any values that can't be converted to ints unchanged:

    import re
    
    def tryint(x):
        try:
            return int(x)
        except ValueError:
            return x
    
    def splittedname(s):
        return tuple(tryint(x) for x in re.split('([0-9]+)', s))
    

    To sort a list of names, use splittedname as a key function to sorted:

    >>> names = ['YT4.11', '4.3', 'YT4.2', '4.10', 'PT2.19', 'PT2.9']
    >>> sorted(names, key=splittedname)
    ['4.3', '4.10', 'PT2.9', 'PT2.19', 'YT4.2', 'YT4.11']
    

提交回复
热议问题