假设有一个列表,列表中嵌套元组,每个元组的第一个值是水果名称,第二个是喜爱程度。
问题:按照喜爱程度对该列表排序
fruit = [('apple',7),('orange',4),('melon',9),('pear',6)]
方法一:
import operator
fruit.sort(key=operator.itemgetter(1),reverse=True)
output:[('melon', 9), ('apple', 7), ('pear', 6), ('orange', 4)]
方法二:
sorted(fruit, key=lambda x: x[1],reverse=True)
output:[('melon', 9), ('apple', 7), ('pear', 6), ('orange', 4)]
需要注意的是方法一直接对原始列表进行修改
本文介绍了两种在Python中对嵌套元组列表按特定字段排序的方法。一种使用内置的operator模块,另一种使用lambda表达式配合sorted函数。通过实例演示了如何对包含水果名称和喜爱程度的列表进行排序。
1828

被折叠的 条评论
为什么被折叠?



