Python 程序用于在词典中找到最高 3 个值
在本文中,我们将了解解决方案和方法来解决给定的问题陈述。
问题陈述
给定一个词典,我们需要找出三个最高值并展示出来。
方法 1 − 使用 collection 模块(计数器函数)
示例
from collections import Counter
# Initial Dictionary
my_dict = {'t': 3, 'u': 4, 't': 6, 'o': 5, 'r': 21}
k = Counter(my_dict)
# Finding 3 highest values
high = k.most_common(3)
print("Dictionary with 3 highest values:")
print("Keys: Values")
for i in high:
print(i[0]," :",i[1]," ")输出
Dictionary with 3 highest values: Keys: Values r : 21 t : 6 o : 5
方法 2 − 使用 heapq 模块(nlargest 函数)
示例
from collections import Counter
# Initial Dictionary
my_dict = {'t': 3, 'u': 4, 't': 6, 'o': 5, 'r': 21}
k = Counter(my_dict)
# Finding 3 highest values
high = k.most_common(3)
print("Dictionary with 3 highest values:")
print("Keys: Values")
for i in high:
print(i[0]," :",i[1]," ")输出
Dictionary with 3 highest values: Keys: Values r : 21 t : 6 o : 5
结论
在本文中,我们学习了将十进制数转换为二进制数的方法。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP