Sort list of strings by integer suffix in python

后端 未结 4 1208
时光说笑
时光说笑 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 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.

提交回复
热议问题