如何在Python中進行字典計算?


問題

你想要對一個包含資料的字典進行各種計算(例如,最小值、最大值、排序等)。

解決方案。

我們將建立一個包含網球運動員及其大滿貫冠軍數量的字典。

PlayerTitles = {
   'Federer': 20,
   'Nadal': 20,
   'Djokovic': 17,
   'Murray': 3,
   'Theim' : 1,
   'Zverev': 0
}

1.我們有一個字典,包含球員姓名和每個球員贏得的大滿貫冠軍數量。現在讓我們嘗試找出獲得冠軍數量最少的球員。

#type(PlayerTitles)
print(f"Output \n*** The minimum value in the dictionary is {min(PlayerTitles)} ")

輸出

*** The minimum value in the dictionary is Djokovic

2. 這可能不是我們想要的結果,因為我們實際上是在嘗試對字典值進行計算。所以讓我們嘗試使用字典的 values() 方法來解決這個問題。

print(f"Output \n*** The minimum value in the dictionary is {min(PlayerTitles.values())} ")

輸出

*** The minimum value in the dictionary is 0

3. 不幸的是,這通常也不是你真正想要的。例如,你可能想知道有關相應鍵的資訊,即獲得冠軍數量最少的球員的姓名。

4. 如果你為 min() 和 max() 提供一個 key 函式,你可以獲得與最小值或最大值對應的鍵。

print(f"Output \n***{min(PlayerTitles, key=lambda k: PlayerTitles[k])} ")

輸出

***Zverev

5. 但是,要獲得最小值,你需要進行額外的查詢。

min_titles = PlayerTitles[min(PlayerTitles, key=lambda k: PlayerTitles[k])]
print(f"Output \n***{min_titles} ")

輸出

***0

6. 使用 zip() 的解決方案透過將字典“反轉”為 (value, key) 對的序列來解決問題。當對這樣的元組進行比較時,首先比較值元素,然後比較鍵。

這給了我們我們想要的行為,並允許使用單個語句輕鬆地對字典內容進行簡化和排序。

min_titles = min(zip(PlayerTitles.values(), PlayerTitles.keys()))
max_titles = max(zip(PlayerTitles.values(), PlayerTitles.keys()))

print(f"Output \n***{min_titles , max_titles} ")

輸出

***((0, 'Zverev'), (20, 'Nadal'))

7.類似地,要對資料進行排名,請將 zip() 與 sorted() 一起使用。

titles_sorted = sorted(zip(PlayerTitles.values(), PlayerTitles.keys()))
print(f"Output \n***{titles_sorted} ")

輸出

***[(0, 'Zverev'), (1, 'Theim'), (3, 'Murray'), (17, 'Djokovic'), (20, 'Federer'), (20, 'Nadal')]

8. 在進行這些計算時,請注意 zip() 建立一個迭代器,只能使用一次。

titles_and_players = zip(PlayerTitles.values(), PlayerTitles.keys())
print(f"Output \n***{min(titles_and_players)} ")

輸出

***(0, 'Zverev')

9. 如果我們再次嘗試呼叫它,我們將面臨空序列異常。

10. 應該注意的是,在涉及 (value, key) 對的計算中,如果多個條目碰巧具有相同的值,則將使用鍵來確定結果。

例如,在 min() 和 max() 等計算中,如果存在重複值,則將返回鍵最小或最大的條目。這就是為什麼當我們選擇獲得最多冠軍的球員時,最終只得到一個值,即納達爾。(參見步驟 7 輸出)。

更新於:2020年11月9日

2K+ 次瀏覽

啟動您的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.