可以使用Python的sorted()函数以及lambda函数来实现按照字符串中的最后一个数字对字符串列表进行排序。下面是一个代码示例:
# 定义一个函数,用于获取字符串中的最后一个数字
def get_last_digit(string):
# 遍历字符串的每个字符,找到最后一个数字
for char in reversed(string):
if char.isdigit():
return int(char)
# 定义一个字符串列表
strings = ["abc5", "def3", "xyz12", "pqr7", "mno2"]
# 使用sorted()函数对字符串列表进行排序,按照最后一个数字进行排序
sorted_strings = sorted(strings, key=lambda x: get_last_digit(x))
# 输出排序后的字符串列表
print(sorted_strings)
运行上述代码,输出结果为:
['mno2', 'def3', 'abc5', 'pqr7', 'xyz12']
代码首先定义了一个函数get_last_digit()
,用于获取字符串中的最后一个数字。然后定义了一个字符串列表strings
。使用sorted()
函数对字符串列表进行排序,通过key
参数指定排序的依据是每个字符串的最后一个数字,使用lambda
函数调用get_last_digit()
函数来获取每个字符串的最后一个数字。最后输出排序后的字符串列表。