How to sort a list by last character of string

后端 未结 4 881
渐次进展
渐次进展 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条回答
  •  Happy的楠姐
    2021-02-19 14:18

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

    >>> s = ["Tiger 6", "Shark 4", "Cyborg 8"]
    >>> sorted(s, key=lambda x: int(x[-1]))
    ['Shark 4', 'Tiger 6', 'Cyborg 8']
    

    Try this if there are more num of digits at the last.

    >>> import re
    >>> sorted(s, key=lambda x: int(re.search(r'\d+$',x).group()))
    ['Shark 4', 'Tiger 6', 'Cyborg 8']
    

    re.search(r'\d+$',x).group() helps to fetch the number present at the last irrespective of preceding space.

提交回复
热议问题