Python – 按字符串列表中的后置字符排序
pythonserver side programmingprogramming更新于 2025/10/20 17:48:17
当需要按后置字符对列表进行排序时,会定义一个使用负索引返回结果的方法。
示例
下面是相同的演示 −
def get_rear_position(element):
return element[-1]
my_list = ['python', 'is', 'fun', 'to', 'learn']
print("列表为: ")
print(my_list)
my_list.sort(key = get_rear_position)
print("结果为: ")
print(my_list)
输出
列表为: ['python', 'is', 'fun', 'to', 'learn'] 结果为: ['python', 'fun', 'learn', 'to', 'is']
解释
定义一个方法,将列表的元素作为参数,并使用负索引返回最后一个元素作为输出。
定义一个列表并显示在控制台上。
现在使用 key 作为先前定义的方法对列表进行排序。
这是显示在控制台上的输出。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

