บทนำ
การตรวจสอบว่า tuple มีโครงสร้างชนิดข้อมูลตามลำดับที่กำหนดหรือไม่ สามารถทำได้โดยใช้ isinstance() ร่วมกับการเชื่อมเงื่อนไขด้วย and (chained condition)
ตัวอย่างโค้ด
my_tuple = ('Hi', ['there', 'Will'], 67)
print("Tuple:", my_tuple)
# ตรวจสอบลำดับ: str, list, int
check = (isinstance(my_tuple, tuple) and
isinstance(my_tuple[0], str) and
isinstance(my_tuple[1], list) and
isinstance(my_tuple[2], int))
print("โครงสร้างตรงตามที่กำหนดหรือไม่?", check)
ผลลัพธ์
Tuple: ('Hi', ['there', 'Will'], 67)
โครงสร้างตรงตามที่กำหนดหรือไม่? True
คำอธิบาย
isinstance(obj, type)คืนค่า True ถ้า obj เป็น instance ของ type นั้น (รวม subclass)- ใช้
andเชื่อมทุกเงื่อนไข ต้องเป็นจริงทุกอย่างจึงได้ True - ตรวจสอบได้ทั้งว่าเป็น tuple และ element แต่ละตัวมีชนิดถูกต้อง
การประยุกต์ใช้: ฟังก์ชันตรวจสอบโครงสร้าง
def validate_structure(tup, *expected_types):
"""ตรวจสอบว่า tuple tup มีชนิดข้อมูลตาม expected_types"""
if not isinstance(tup, tuple) or len(tup) != len(expected_types):
return False
return all(isinstance(val, t) for val, t in zip(tup, expected_types))
# ใช้งาน
print(validate_structure(('Hi', [1,2], 67), str, list, int)) # True
print(validate_structure(('Hi', 'there', 67), str, list, int)) # False