基於Python中元組首元素出現次數的排序
當需要根據元組首元素出現的次數對元組進行排序時,可以使用`dict.fromkeys`方法。
列表可以用來儲存異構值(即任何資料型別的資料,如整數、浮點數、字串等)。
元組列表基本上包含在列表中包含的元組。
`dict.fromkeys`方法將返回一個具有特定鍵和值的字典。
下面是一個演示:
示例
def sort_on_occurence(my_lst):
my_dict = {}
for i, j in my_lst:
my_dict.setdefault(i, []).append(j)
return([(i, *dict.fromkeys(j), len(j))
for i, j in my_dict.items()])
my_list = [(1, 'Harold'), (12, 'Jane'), (4, 'Paul'), (7, 'Will')]
print("The list of tuples is")
print(my_list)
print("The list after sorting by occurence is")
print(sort_on_occurence(my_list))輸出
The list of tuples is [(1, 'Harold'), (12, 'Jane'), (4, 'Paul'), (7, 'Will')] The list after sorting by occurence is [(1, 'Harold', 1), (12, 'Jane', 1), (4, 'Paul', 1), (7, 'Will', 1)]
解釋
- 定義了一個名為`sort_on_occurence`的方法,該方法將元組列表作為引數。
- 建立一個新的字典。
- 遍歷元組列表,並在空字典中設定預設值。
- 定義了一個元組列表,並在控制檯上顯示。
- 透過傳遞上面定義的元組列表來呼叫該函式。
- 這是在控制檯上顯示的輸出。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP