บทนำ
การตรวจสอบว่า tuple ประกอบด้วยค่า None ทั้งหมดหรือไม่ สามารถทำได้ด้วยฟังก์ชัน all() ร่วมกับ generator expression
ตัวอย่างโค้ด
my_tuple = (None, None, None, None, None, None, None)
print("Tuple:", my_tuple)
# ตรวจสอบทุก element เป็น None
all_none = all(elem is None for elem in my_tuple)
print("มีแค่ None หรือไม่?", all_none)
ผลลัพธ์
Tuple: (None, None, None, None, None, None, None) มีแค่ None หรือไม่? True
คำอธิบาย
elem is Noneตรวจสอบ identity (เร็วกว่า == และปลอดภัยกว่า)all(...)คืน True ถ้าทุก element ใน generator เป็น True- Short-circuit: หาเจอค่าที่ไม่ใช่ None จะหยุดทันทีคืน False
กรณี Tuple ว่าง
empty = () print(all(x is None for x in empty)) # True (vacuously true)
Tuple ว่าง all() คืน True เสมอ (ไม่มี element ที่เป็น False)
การประยุกต์: ตรวจสอบว่ามี None อยู่อย่างน้อย 1 ตัว
has_none = any(elem is None for elem in my_tuple)
print("มี None อยู่ไหม?", has_none)
สรุป
- ทั้งหมดเป็น None →
all(x is None for x in tup) - มี None อย่างน้อย 1 ตัว →
any(x is None for x in tup) - ไม่มี None เลย →
all(x is not None for x in tup)