How to sort a list by last character of string

后端 未结 4 850
渐次进展
渐次进展 2021-02-19 13:56

I am trying to write a program that orders a list of strings based on the last character in the item.

[\"Tiger 6\", \"Shark 4\", \"Cyborg 8\"] are how my li

4条回答
  •  南笙
    南笙 (楼主)
    2021-02-19 14:09

    If the numbers are not single digits, you can try -

    >>> l = ["Tiger 6", "Shark 4", "Cyborg 8", "Temporary 12"]
    >>> l.sort(key = lambda x: int(x.rsplit(' ',1)[1]))
    >>> l
    ['Shark 4', 'Tiger 6', 'Cyborg 8', 'Temporary 12']
    

    str.rsplit(s, n) function starts splitting the string at the end towards start of the string and stops after n splits. In the above case, it only splits the string once, at a space.

提交回复
热议问题