บทนำ
การตรวจสอบชนิดข้อมูล (data type) ของแต่ละ element ใน tuple สามารถทำได้ง่ายๆ โดยใช้ map() ร่วมกับฟังก์ชัน type() แล้วแปลงเป็นลิสต์เพื่อดูผลลัพธ์
ตัวอย่างโค้ด
my_tuple = ('Hi', 23, ['there', 'Will'])
print("Tuple:", my_tuple)
# ใช้ map เรียก type() กับแต่ละ element
types_list = list(map(type, my_tuple))
print("ชนิดข้อมูลแต่ละตัว:", types_list)
ผลลัพธ์
Tuple: ('Hi', 23, ['there', 'Will'])
ชนิดข้อมูลแต่ละตัว: [<class 'str'>, <class 'int'>, <class 'list'>]
คำอธิบาย
map(type, my_tuple)ใช้ฟังก์ชันtypeกับทุก element ใน tuplelist(...)แปลง map object เป็นลิสต์เพื่อแสดงผล- ผลลัพธ์แสดง class ของแต่ละค่า: str, int, list
การใช้งานเพิ่มเติม
# แสดงแค่ชื่อชนิดข้อมูล (string)
type_names = [type(x).__name__ for x in my_tuple]
print(type_names) # ['str', 'int', 'list']
# ตรวจสอบเฉพาะชนิดที่ต้องการ
has_list = any(isinstance(x, list) for x in my_tuple)
print("มี list อยู่ไหม?", has_list) # True