Python程式提取N個最大字典鍵


Python字典是一種資料結構,可用於多種操作,使其成為一種多產的程式設計工具。它以鍵值對的形式儲存資料,即每個資料都可以用唯一的鍵標記。字典中的鍵是與不同值關聯的識別符號,可以訪問、修改和刪除這些值。

根據任務,鍵可以按不同順序排序和提取。在本文中,我們將討論提取**N個最大**字典鍵的類似概念。我們將對這些唯一鍵進行操作並提取相關資料。

理解問題

考慮一個具有隨機唯一鍵值的字典,我們的任務是從字典中分離出**最大的N個**鍵。讓我們藉助一個示例來理解這一點:

輸入輸出場景

讓我們考慮一個具有以下值的字典:

Input:
dict1 = {12 : 10, 22 : 12, 18 : 4, 4 : 8, 20 : 14, 9 : 13}

如果N的值為4,則應返回原始字典中4個最大的鍵值。

Output: [22, 20, 18, 12]

返回最大N個鍵值。既然我們已經瞭解了問題陳述,那麼讓我們討論一些解決方案。

使用迭代和max()

這是從字典中提取N個最大鍵的基本方法。我們將建立一個字典和兩個空列表,分別儲存最大值和參考值。在此之後,我們將傳遞“**N**”值並藉助迭代和“**.items()**”方法提取鍵值。

這些提取的值將儲存在一個列表(Maxlis)中。我們將再次迭代附加的字典鍵“**N**”次並提取所有最大值。在每次迭代中,最大鍵值將從列表中刪除,並且包含最大N個鍵的列表(Nlargest)將被列印。

示例

以下是如何使用迭代和追加提取N個最大字典鍵的示例:

dict1 = {12 : 10, 22 : 12, 18 : 4, 4 : 8, 20 : 14, 9 : 13}
Maxlis = []
N = 4
Nlargest = []
print(f"The original dictionary is: {dict1}")

for keys, values in dict1.items():
   Maxlis.append(keys)

for x in range(N):
   maxval = max(Maxlis)
   Nlargest.append(maxval)
   Maxlis.remove(maxval)

print(f"The list of N largest dictionaries keys: {Nlargest}")

輸出

The original dictionary is: {12: 10, 22: 12, 18: 4, 4: 8, 20: 14, 9: 13}
The list of N largest dictionaries keys: [22, 20, 18, 12]

使用迭代以及sorted() + lambda

這是提取N個最大鍵的高階方法。在這種方法中,我們將使用迭代和“.items()”方法檢索所有字典鍵。我們將在“**sorted()**”函式的“**key**”引數中指定另一個函式(**lambda**)來處理提取邏輯。lambda函式提取鍵,sorted()函式按順序對它們進行排序。

“**reverse = True**”子句按降序對鍵值進行排序。最後,我們使用**切片**技術僅從字典中提取前N個鍵,並將它們儲存在一個列表(Nlargest)中。

示例

以下是一個示例:

dict1 = {12 : 10, 22 : 12, 18 : 4, 4 : 8, 20 : 14, 9 : 13}
N = 4
Nlargest = []
print(f"The original dictionary is: {dict1}")

for keys, values in sorted(dict1.items(), key = lambda item : item[0],
   reverse = True) [:N]:
   Nlargest.append(keys)
print(f"The N largest keys are: {Nlargest}")

輸出

The original dictionary is: {12: 10, 22: 12, 18: 4, 4: 8, 20: 14, 9: 13}
The N largest keys are: [22, 20, 18, 12]

使用sorted() + itemgetter()

代替使用lambda函式進行項提取,我們可以使用**operator**模組中的“**itemgetter()**”函式。我們將使用迭代和排序鍵的相同概念,但“**key**”引數將為鍵的提取分配“**itemgetter()**”函式。

示例

以下是一個示例:

from operator import itemgetter
dict1 = {12 : 10, 22 : 12, 18 : 4, 4 : 8, 20 : 14, 9 : 13}
N = 4
Nlargest = []
print(f"The original dictionary is: {dict1}")

for keys, values in sorted(dict1.items(), key = itemgetter(0),
   reverse = True) [:N]:
   Nlargest.append(keys)
print(f"The N largest keys are: {Nlargest}")

輸出

The original dictionary is: {12: 10, 22: 12, 18: 4, 4: 8, 20: 14, 9: 13}
The N largest keys are: [22, 20, 18, 12]

其他解決方案和見解

有幾種技術可用於從字典中提取最大的N個鍵,包括使用“**heapq**”模組中的“**nlargest()**”函式和基於函式的排序。為“**lambda**”和“**itemgetter**”函式設定正確的值非常關鍵,因為它為項排序和提取奠定了基礎。

結論

在本文中,我們討論了提取N個最大字典值的多種解決方案。我們從分離和追加最大鍵的基本和蠻力方法開始。在此之後,我們討論了一些高階解決方案來生成細緻且最佳化的程式。我們瞭解了sorted()、lambda、itemgetter和max()函式的應用。

更新於:2023年7月12日

174次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.