Python 按最后一个字符对列表排序
我正在尝试创建一个程序,该程序将按最后一个字符对列表进行排序Python 按最后一个字符对列表排序,python,Python,我正在尝试创建一个程序,该程序将按最后一个字符对列表进行排序 ["Apple", "Mellon", "Banana"] 这是我的清单,我需要把它们整理好 ["Banana", "Apple", "Mellon"] 您可以使用函数进行排序,这里我们使用lambda函数,它查看列表中字符串的最后一个索引 lst = ["Apple", "Mellon", "Banana"] sorted(lst, key=lambda x: x[-1]) [‘香蕉’、‘苹果’、‘梅隆’] 无需复制列表,即
["Apple", "Mellon", "Banana"]
这是我的清单,我需要把它们整理好
["Banana", "Apple", "Mellon"]
您可以使用函数进行排序,这里我们使用lambda函数,它查看列表中字符串的最后一个索引
lst = ["Apple", "Mellon", "Banana"]
sorted(lst, key=lambda x: x[-1])
[‘香蕉’、‘苹果’、‘梅隆’]
无需复制列表,即可应用
.sort()
。这是一种内存效率更高的方法
lst.sort(key=lambda x: x[-1])
print(lst)
[‘香蕉’、‘苹果’、‘梅隆’]
通过为
键
属性传递lambda
表达式,可以使用排序
方法
此方法不返回任何值,但会更改原始列表
输出
['Banana', 'Apple', 'Mellon']
到目前为止,您尝试了什么?
sorted(lst)
创建了一个新列表lst.sort()
对现有的就地排序。我相信OP想要第二种风格。或者使用操作符.itemgetter
和itemgetter(-1)
。
['Banana', 'Apple', 'Mellon']