Sort list of strings by integer suffix in python

后端 未结 4 1193
时光说笑
时光说笑 2021-01-02 14:28

I have a list of strings:

[song_1, song_3, song_15, song_16, song_4, song_8]

I would like to sort them by the # at the end, unfortunately s

4条回答
  •  梦毁少年i
    2021-01-02 14:54

    Well, you want to sort by the filename first, then on the int part:

    def splitter( fn ):
        try:
            name, num = fn.rsplit('_',1)  # split at the rightmost `_`
            return name, int(num)
        except ValueError: # no _ in there
            return fn, None
    
    sorted(the_list, key=splitter)
    

提交回复
热议问题