按指定順序對 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