python排序元组列表
时间:2020-02-23 14:43:20 来源:igfitidea点击:
在本教程中,我们将在各种标准的基础上看到如何对元组列表进行排序。
让我们在例子的帮助下,假设我们有以下元组列表:
#tuple having structure (name,age,salary) l=[("Mohan",21,20000),("John",19,10000),("hyman",23,25000),("igi",20,5000),("Martin",27,7000)]
现在我们想根据年龄和年龄的年龄对元组进行排序列表,是元组中的第一个索引。
我们可以使用以下代码来根据年龄对元组列表进行排序。
#tuple having structure (name,age,salary) l=[("Mohan",21,20000),("John",19,10000),("hyman",23,25000),("igi",20,5000),("Martin",27,7000)] sortList=sorted(l, key=lambda x: x[1]) print("Sorted list of tuples based on age:",sortList)
输出:
Sorted list of tuples based on age: [('John', 19, 10000), ('igi', 20, 5000), ('Mohan', 21, 20000), ('hyman', 23, 25000), ('Martin', 27, 7000)]
如果要按降序排序,那么我们只需要添加Reversed = True如下所示。
#tuple having structure (name,age,salary) l=[("Mohan",21,20000),("John",19,10000),("hyman",23,25000),("igi",20,5000),("Martin",27,7000)] sortList=sorted(l, key=lambda x: x[1],reverse=True) print("Sorted list of tuples based on age in descending order:",sortList)
输出:
Sorted list of tuples based on age: [('Martin', 27, 7000), ('hyman', 23, 25000), ('Mohan', 21, 20000), ('igi', 20, 5000), ('John', 19, 10000)]
让我们在薪水的基础上排序元组列表。
#tuple having structure (name,age,salary) l=[("Mohan",21,20000),("John",19,10000),("hyman",23,25000),("igi",20,5000),("Martin",27,7000)] #Sorting by salary(2nd index of tuple) sortList=sorted(l, key=lambda x:x[2]) print("Sorted list of tuples based on salary:",sortList)
输出:
Sorted list of tuples based on age in descending order: [('igi', 20, 5000), ('Martin', 27, 7000), ('John', 19, 10000), ('Mohan', 21, 20000), ('hyman', 23, 25000)]