在 Python 字典中尋找最大值
-
使用
operator.itemgetter()方法獲取具有最大值的鍵 -
在 Python 3.x 中使用
dict.items()方法來獲取字典中的最大值的鍵 - 獲取字典中最大值的鍵的通用和高記憶體效率的解決方案
-
使用
max()和dict.get()方法來獲取字典中最大值的鍵
本教程介紹瞭如何在 Python 中獲取一個具有最大值的鍵。由於該方法與以前的 Python 版本相比已經發生了變化,因此它還列出了一些示例程式碼來澄清概念。
使用 operator.itemgetter() 方法獲取具有最大值的鍵
我們不需要建立一個新的列表來迭代字典的 (key, value) 對。我們可以使用 stats.iteritems() 來實現這個目的。它在字典的 (key, value) 對上返回一個迭代器。
你可以使用 operator.itemgetter(x) 方法來獲得可呼叫的物件,它將從物件中返回索引為 x 的元素。這裡因為物件是 (key, value) 對,所以 operator.itemgetter(1) 指的是 1 索引處的元素,也就是 value。
由於我們想要一個具有最大值的鍵,所以我們將把方法封裝在 max 函式中。
下面給出了這個方法的基本示例程式碼。
import operator
stats = {"key1": 20, "key2": 35, "key3": 44}
max_key = max(stats.iteritems(), key=operator.itemgetter(1))[0]
print(max_key)
輸出:
key3
另外,請注意,iteritems() 在從字典中新增或刪除項時可能會引發 RunTimeException,而 dict.iteritems 在 Python 3 中被刪除。
在 Python 3.x 中使用 dict.items() 方法來獲取字典中的最大值的鍵
在 Python 3.x 中,你可以使用 dict.items() 方法來迭代字典中的 key-value 對。它與 Python 2 中的 dict.iteritems() 方法相同。
下面給出了這個方法的示例程式碼。
import operator
stats = {"key1": 20, "key2": 35, "key3": 44}
max_key = max(stats.items(), key=operator.itemgetter(1))[0]
print(max_key)
輸出:
key3
獲取字典中最大值的鍵的通用和高記憶體效率的解決方案
有趣的是,有另一種解決方案對 Python 2 和 Python 3 都適用。該方案使用 lambda 函式來獲取 key,並使用 max 方法來確保獲取的 key 是最大的。
下面給出了這種方法的程式碼。
import operator
stats = {"key1": 20, "key2": 35, "key3": 44}
max_key = max(stats, key=lambda key: stats[key])
print(max_key)
輸出:
key3
使用 max() 和 dict.get() 方法來獲取字典中最大值的鍵
解決這個問題的另一個方法可以簡單地使用內建的 max() 方法。它提供了 stats 來獲取最大值,為了返回具有最大值的 key,使用 dict.get() 方法。
下面給出一個示例程式碼。
import operator
stats = {"key1": 20, "key2": 35, "key3": 44}
max_key = max(stats, key=stats.get)
print(max_key)
輸出:
key3
Syed Moiz is an experienced and versatile technical content creator. He is a computer scientist by profession. Having a sound grip on technical areas of programming languages, he is actively contributing to solving programming problems and training fledglings.
LinkedIn