Bài toán: cho dictionary, in 3 giá trị lớn nhất.
Cách 1: Dùng collections.Counter
Counter.most_common(n) trả về n phần tử phổ biến nhất (giá trị lớn nhất).
from collections import Counter
my_dict = {'T': 23, 'U': 22, 'T': 21, 'O': 20, 'R': 32, 'S': 99}
k = Counter(my_dict)
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 S : 99 R : 32 U : 22
Cách 2: Dùng heapq.nlargest
nlargest(n, iterable, key) lấy n phần tử lớn nhất theo key.
from heapq import nlargest
my_dict = {'T': 23, 'U': 22, 'T': 21, 'O': 20, 'R': 32, 'S': 99}
ThreeHighest = nlargest(3, my_dict, key=my_dict.get)
print("Dictionary with 3 highest values:")
print("Keys : Values")
for val in ThreeHighest:
print(val, " : ", my_dict.get(val))
Dictionary with 3 highest values: Keys : Values S : 99 R : 32 U : 22
Kết luận
Đã học 2 cách tìm 3 giá trị lớn nhất trong dictionary: Counter.most_common() và heapq.nlargest().