如何按字符串的最后一个字符对列表进行排序 [英] How to sort a list by last character of string
问题描述
我正在尝试编写一个程序,该程序根据项目中的最后一个字符对字符串列表进行排序.
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"]
是我的列表的导入方式,但是我需要根据末尾的数字将它们按数字顺序放置.
["Tiger 6", "Shark 4", "Cyborg 8"]
are how my list is imported, but I need to put them in numerical order based on the numbers at the end.
推荐答案
我正在尝试编写一个程序,该程序根据项目中的最后一个字符对字符串列表进行排序.
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()
有助于获取最后一个存在的数字,而与前面的空格无关.
re.search(r'\d+$',x).group()
helps to fetch the number present at the last irrespective of preceding space.
这篇关于如何按字符串的最后一个字符对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!