【Python 必会技巧】获取字典中(多个)最大值(value)的键(key)
生活随笔
收集整理的這篇文章主要介紹了
【Python 必会技巧】获取字典中(多个)最大值(value)的键(key)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
先總結一下,分為以下四種情況:
- 情況一:最大值只有一個,只獲取最大值(value)所對應的鍵(key)
- 情況二:最大值只有一個,同時獲取最大值(value)和所對應的鍵(key)
- 情況三:最大值有多個,獲取所有最大值(value)所對應的鍵(key)
| 情況一:最大值只有一個,只獲取最大值的鍵 |
方法一:使用 get
>>> dict = {'two': 2, 'one': 1, 'four': 4, 'three': 3} >>> print(max(dict, key=dict.get)) four方法二:lambda 匿名函數
>>> dict = {'two': 2, 'one': 1, 'four': 4, 'three': 3} >>> print(max(dict, key=lambda i: dict[i])) four方法三:operator 模塊中的 itemgetter 函數
>>> import operator >>> >>> dict = {'two': 2, 'one': 1, 'four': 4, 'three': 3} >>> print(max(dict.items(), key=operator.itemgetter(1))[0]) fouroperator 模塊的 itemgetter 函數用于獲取對象的哪些維的數據,參數為一些序號,以下舉例說明:
>>> import operator >>> >>> a = [1, 2, 3, 4] >>> b = operator.itemgetter(0) # 定義函數b,獲取對象的第0個域的值 >>> print(b(a)) 1 >>> b = operator.itemgetter(0, 1) # 定義函數b,獲取對象的第0個和第1個域的值 >>> print(b(a)) (1, 2)| 情況二:最大值只有一個,同時獲取最大值和對應的鍵 |
方法一:operator 模塊中的 itemgetter 函數
>>> import operator >>> >>> dict = {'two': 2, 'one': 1, 'four': 4, 'three': 3} >>> print(sorted(dict.items(), key=operator.itemgetter(1), reverse=True)[0]) ('four', 4)方法二:zip 方法
>>> dict = {'two': 2, 'one': 1, 'four': 4, 'three': 3} >>> print(max(zip(dict.values(), dict.keys()))) (4, 'four')| 情況三:最大值有多個,獲取所有最大值的鍵 |
總結
以上是生活随笔為你收集整理的【Python 必会技巧】获取字典中(多个)最大值(value)的键(key)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为nova 10 Pro真机曝光:竖向
- 下一篇: 霸气!红旗LS7双色版外观亮相:劳斯莱斯