tutorial นี้เราจะมาสอนเขียน Python function ง่ายๆเพื่อใช้วิเคราะห์ข้อมูล โดย input
คือ list of items ส่วน output
จะออกมาเป็น dictionary (key คือชื่อ item และ value คือจำนวน item นั้นๆ)
สำหรับเพื่อนๆที่อยากทำตาม tutorial นี้ ต้องเข้าใจสองเรื่องนี้ก่อน
- list vs. dictionary
- control flow (if-else และ for loop)
ถ้าใครยังใหม่กับ Python ลองดูคอร์สฟรีของเราก่อนที่ https://datarockie.com/p/python-for-non-programmer
Count Animals
โจทย์คือเราต้องการนับจำนวน dog, cat, hippo ที่อยู่ใน list animals
วิธีการที่เราจะแก้ปัญหาใน Python จะเริ่มจากการสร้าง empty dictionary ขึ้นมาก่อน (line 8)
ตั้งแต่ line 12-16 คือการเขียน for loop เพื่อนับ item ทีละตัวที่อยู่ใน animals
ภายใน for loop เราเขียน if-else เพื่อเช็คชื่อ animal ตัวนั้นและอัพเดท key-value ใน result dictionary
# input | |
animals = ['dog', 'cat', 'cat', 'dog', 'dog', 'dog', 'cat', 'dog', 'hippo'] | |
# expected output | |
# result = {'dog':5, 'cat':3, 'hippo':1} | |
# create empty dict to save our output | |
result = {} | |
# we write for loop and if-else | |
# to check every item in the animals list | |
for animal in animals: | |
if animal in result: | |
result[animal] += 1 | |
else: | |
result[animal] = 1 | |
# print output | |
print(result) |
if
animal in
result: คือเงื่อนไขที่เราใช้ตรวจสอบว่ามีชื่อ animal ตัวนั้นอยู่ใน result dictionary ของเราหรือยัง?
- if True – เราจะอัพเดท result ด้วยโค้ด result[animal] += 1
- if False – เราจะอัพเดท result ด้วยโค้ด result[animal] = 1
ทำไม if False เราถึงเขียน result[animal] = 1? เพราะ for loop รอบนั้นคือการเจอชื่อ animal ตัวนั้นเป็นครั้งแรก เราเลยอัพเดท result dictionary {key: value} ด้วย {ชื่อ animal: 1}
เมื่อ for loop วิ่งครบทุก item ที่อยู่ใน list animals
แล้ว เราจะได้ result dictionary หน้าตาแบบนี้ {‘dog’:5, ‘cat’:3, ‘hippo’:1} ลอง print(result) ออกมาตรวจสอบความถูกต้องอีกครั้งหนึ่ง
Function
เราสามารถเขียน wrap โค้ดด้านบนเป็น function เพื่อนำไปใช้นับ items ใน list อื่นได้
ข้อดีของ function คือ reusable ใช้ซ้ำได้เรื่อยๆ ไม่ต้องเขียนโค้ดใหม่ให้เมื่อยมือ 😛
ใน Python เราสร้างฟังชั่นใช้เองง่ายๆด้วย def
keyword บรรทัดสุดท้ายของฟังชั่นเราใช้ return
keyword เพื่อ return ผลลัพธ์ที่ได้จากฟังชั่น ดูโค้ดตัวอย่างด้านล่าง
# write a reusable function | |
def count_item(input_list): | |
"""count item in a list, return a dict""" | |
result = {} | |
for item in input_list: | |
if item in result: | |
result[item] += 1 | |
else: | |
result[item] = 1 | |
return result |
Testing
ลองทดสอบ count_item()
กับ list อื่นๆ ว่ามันให้ผลลัพธ์อย่างที่เราต้องการหรือเปล่า
# input | |
animals = ['dog', 'cat', 'cat', 'dog', 'dog', 'dog', 'cat', 'dog', 'hippo'] | |
genders = ['M', 'F', 'F', 'F', 'M'] | |
balls = ['red', 'red', 'blue', 'blue', 'blue', 'black'] | |
# test function | |
print(count_item(animals)) | |
print(count_item(genders)) | |
print(count_item(balls)) |
Well done !! ใน tutorial นี้เราเรียนวิธีการเขียนฟังชั่นๆง่าย เพื่อนับจำนวน items ใน list และ return ผลลัพธ์ในรูปแบบของ dictionary
Leave a Reply