Sort list of strings by integer suffix in python

后端 未结 4 1177
时光说笑
时光说笑 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条回答
  • 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)
    
    0 讨论(0)
  • 2021-01-02 14:57
    def number_key(name):
       parts = re.findall('[^0-9]+|[0-9]+', name)
       L = []
       for part in parts:
           try:
              L.append(int(part))
           except ValueError:
              L.append(part)
       return L
    sorted(your_list, key=number_key)
    
    0 讨论(0)
  • 2021-01-02 15:01

    You're close.

    sorted(the_list, key = lambda x: int(x.split("_")[1]))
    

    should do it. This splits on the underscore, takes the second part (i.e. the one after the first underscore), and converts it to integer to use as a key.

    0 讨论(0)
  • 2021-01-02 15:07
    sorted(the_list, key = lambda k: int(k.split('_')[1]))
    
    0 讨论(0)
提交回复
热议问题