รู้จักกับ Pattern Matching ใน Python
--
Pattern Matching คืออะไร
โครงสร้างควบคุมแบบกำหนดเงื่อนไขในภาษา Python มีลักษณะการทำงานคล้ายกับคำสั่ง if..else หรือ if..elif…else แต่สามารถทำงานกับชนิดข้อมูลได้หลายค่า ตัวอย่างเช่น List , Tuple , Dictionary , Object (รองรับการทำงานใน Python 3.10 ขึ้นไป)
รูปแบบของ Pattern Matching
- Literal Pattern
- Wildcard Pattern
- Capture Pattern
- OR Pattern
- Sequence Pattern
- Mapping Pattern
- Class Pattern
โครงสร้างคำสั่ง
match expression :
case pattern1 :
#คำสั่งต่างๆ
case pattern2 :
#คำสั่งต่างๆ
case patternN :
#คำสั่งต่างๆ
Literal Pattern เป็น Pattern กำหนดค่าคงที่ เช่น ตัวเลข ชุดข้อความ (String)
ข้อมูลแบบบูลีน (Boolean) หรือ ค่า None
# Literal Pattern
amount = None
match amount:
case 1 :
print("One")
case 2 :
print("Two")
case None:
print("Empty Value")
# ผลลัพธ์จากการเปรียบเทียบเท่ากับเคส None แสดงข้อความ Empty Value
Wildcard Pattern เป็น Pattern ในการเปรียบเทียบทุกๆเคสแล้วไม่ตรงกับ Case
ใดเลย (default case) โดยใช้สัญลักษณ์ _ (Underscore)
# Wildcard Pattern Example#1
service = int(input("ป้อนหมายเลขเพื่อใช้บริการ : "))
match service:
case 1 :
print("ถอนเงิน")
case 2 :
print("ฝากเงิน")
case 3 :
print("เปิดบัญชีใหม่")
case _:
print("หมายเลขไม่ถูกต้อง")
# Wildcard Pattern #Example2
sayHi = input("แสดงข้อความทักทาย : ")
match sayHi:
case "thai" :
print("สวัสดี")
case "english" :
print("Hello")
case _:
print("Unknown")
Capture Pattern เป็น Pattern ที่ใช้ชื่อในการเปรียบเทียบค่า โดยการทำงานเหมือนกับ Wildcard Pattern แต่จะใช้ชื่อในการเปรียบเทียบค่าและนำมาทำงานในเคสนั้น
# Capture Pattern
service = int(input("ป้อนหมายเลขเพื่อใช้บริการ : "))
match service:
case 1 :
print("ถอนเงิน")
case 2 :
print("ฝากเงิน")
case 3 :
print("เปิดบัญชีใหม่")
case service:
print(f"ไม่มีบริการหมายเลข {service} ในระบบ โปรดทำรายการใหม่อีกครั้ง")
Guard เป็นฟิลเตอร์หรือการกำหนดขอบเขตการทำงานภายในเคสโดยใช้งานร่วมกับคำสั่ง if เป็นเงื่อนไขอีกชั้นหลังการเปรียบเทียบค่าในเคส
# Guard
score = int(input("ป้อนคะแนนสอบ : "))
match score:
case 100 :
print("คะแนนเต็ม")
case 50 :
print("ผ่านเกณฑ์")
case score if score>50 and score<100:
print(f"คะแนน {score} อยู่ในช่วง 50 ถึง 100 ถือว่าผ่านเกณฑ์")
OR Pattern ในเคสสามารถกำหนด Pattern ได้หลาย Pattern สำหรับใช้ทำงานร่วมกันเรียกว่า OR Pattern โดยจะแยกด้วยสัญลักษณ์ | และเปรียบเทียบจากด้านซ้ายมือไปด้านขวามือ
#OR Pattern
number = int(input("ป้อนตัวเลข : "))
match number:
case 0 | 2 | 4 :
print("เลขคู่")
case 1 | 3 | 5 :
print("เลขคี่")
Sequence Pattern เป็น Pattern สำหรับเปรียบเทียบข้อมูลที่อยู่ในรูปแบบ List และ Tuple ซึ่งเป็นการกำหนดค่าหลายๆค่าและแตกค่า (Unpacking) เหล่านั้นออกมาตามลำดับ
#Sequence Pattern
list_number=[10,20,30]
match list_number:
case []:
print("ไม่มีข้อมูลใน List")
case [10,20]:
print("มีข้อมูลจำนวน 2 รายการ")
case (10,20,30):
print("มีข้อมูลจำนวน 3 รายการ")
Mapping Pattern เป็น Pattern สำหรับเปรียบเทียบข้อมูลที่อยู่ในรูปแบบ
Key / Value ใช้เปรียบเทียบข้อมูลที่อยู่ในรูปแบบ Dictionary โดยค่า Key / Value ต้องเท่ากันทั้งสองค่า
#Mapping Pattern Example#1
product={"name":"เมาส์","price":500,"type":"computer"}
match product:
case {"type":"computer"}:
print("ได้รับส่วนลด 50%")
case _:
print("ไม่มีส่วนลด")
#Mapping Pattern Example#2
product_list=[
{"name":"เมาส์","price":500,"type":"computer"},
{"name":"เสื้อ","price":1200,"type":"fashion"},
{"name":"กางเกง","price":900,"type":"fashion"}
]
idx = int(input("Enter Index :"))
match product_list[idx]:
case {"type":"computer"}:
print(f"{product_list[idx]} , ได้รับส่วนลด 50%")
case _:
print(f"{product_list[idx]} ,ไม่มีส่วนลด")
Class Pattern เป็น Pattern สำหรับเปรียบเทียบข้อมูล Object ที่ทำงานใน Class โดยเปรียบเทียบ Attribute หรือสมาชิกใน Class ว่ามีค่าเท่ากันหรือไม่
#Class Pattern
class User :
def __init__(self,username,type):
self.username=username
self.type=type
user1=User("kong","member")
match user1:
case User(username="admin",type="admin"):
print("สวัสดีผู้ดูแลระบบ")
case User(type="member"):
print(f"สวัสดีสมาชิก : {user1.username}")
case User():
print("ไม่มีข้อมูลสมาชิกในระบบ")
ติดตามข่าวสารเพิ่มเติมได้ที่ :
🎯 แฟนเพจ : https://www.facebook.com/KongRuksiamTutorial/
🕵 ช่องยูทูป :https://www.youtube.com/c/KongRuksiamOfficial