ในบทความนี้ เราจะเรียนรู้วิธีแก้ปัญหาตามข้อกำหนดด้านล่าง
ข้อกำหนดปัญหา − เราได้รับ Dictionary และต้องพิมพ์ 3 ค่าที่สูงที่สุดใน Dictionary
มี 2 วิธีตามที่อภิปรายด้านล่าง
วิธีที่ 1: ใช้ฟังก์ชัน Collections.Counter()
ตัวอย่าง
# collections module
from collections import Counter
# Dictionary
my_dict = {'T': 23, 'U': 22, 'T': 21, 'O': 20, 'R': 32, 'S': 99}
k = Counter(my_dict)
# 3 ค่าสูงสุด
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
ที่นี่เมธอด most_common() คืนลิสต์ของ n องค์ประกอบที่พบบ่อยที่สุดและจำนวนนับจากมากที่สุดไปน้อยที่สุด
วิธีที่ 2: ใช้ฟังก์ชัน nlargest ของ heapq
ตัวอย่าง
# nlargest module
from heapq import nlargest
# Dictionary
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
ที่นี่เราใช้ n largest element ที่รับอาร์กิวเมนต์ 3 ตัว คือ จำนวนองค์ประกอบที่จะเลือก และอีกสองอาร์กิวเมนท์คือ dictionary และ keys ของมัน
สรุป
ในบทความนี้ เราได้เรียนรู้วิธีหา 3 ค่าสูงสุดใน Dictionary ทั้ง Counter.most_common() และ heapq.nlargest() ให้ผลลัพธ์เดียวกัน