按指定顺序对 Python 中的元组列表进行排序
当需要按特定顺序对元组列表进行排序时,可以使用“sorted”方法。
“sorted”方法用于对列表中的元素进行排序。
可以使用列表来存储异类值(即任何数据类型的数据,如整数、浮点数、字符串等)。元组列表基本上包含列表中的元组。
以下是同样的演示 -
示例
def tuple_sort(my_tup):
return(sorted(my_tup, key = lambda x: x[1]))
my_tuple = [('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)]
print("The list of tuple is : ")
print(my_tuple)
print("The tuple after placing in a specific order is : ")
print(tuple_sort(my_tuple))输出
The list of tuple is :
[('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)]
The tuple after placing in a specific order is :
[('Mahe', 11), ('Aisha', 33), ('Will', 50), ('Root', 65)]说明
- 定义了一个名为“tuple_sort”的方法,它将元组列表作为参数。
- 它使用“sorted”方法根据元组列表中每个元组中的第一个元素对元组列表进行排序。
- 定义了一个元组列表,并显示在控制台上。
- 通过将此元组列表作为参数来调用该函数。
- 此操作的数据存储在变量中。
- 此变量是显示在控制台上的输出。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP