การนับข้อมูลอย่างง่ายดาย

ประเภทข้อมูลใน Python

Jason Myers

Instructor

Collections Module

  • ส่วนหนึ่งของ Standard Library
  • คอนเทนเนอร์ข้อมูลขั้นสูง
ประเภทข้อมูลใน Python

Counter

  • dictionary พิเศษสำหรับนับข้อมูลและวัดความถี่
from collections import Counter

nyc_eatery_count_by_types = Counter(nyc_eatery_types)
print(nyc_eatery_count_by_type)
Counter({'Mobile Food Truck': 114, 'Food Cart': 74, 'Snack Bar': 24,
'Specialty Cart': 18, 'Restaurant': 15, 'Fruit & Vegetable Cart': 4})
print(nyc_eatery_count_by_types['Restaurant'])
15
ประเภทข้อมูลใน Python

ใช้ Counter หาค่าที่พบบ่อยที่สุด

  • เมธอด .most_common() คืนค่าผลลัพธ์เรียงจากมากไปน้อย
print(nyc_eatery_count_by_types.most_common(3))
[('Mobile Food Truck', 114), ('Food Cart', 74), ('Snack Bar', 24)]
ประเภทข้อมูลใน Python

มาฝึกกันเถอะ!

ประเภทข้อมูลใน Python

Preparing Video For Download...