Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Find Whether All Tuples Have Same Length ใน Python: ตรวจสอบความยาว Tuple เท่ากันทุกตัว

ได้ลิสต์ของ Tuple ตรวจสอบว่าทุก Tuple มีความยาวเท่ากันหรือไม่

วิธี 1: ใช้ len() ในลูป For

listA = [('Mon', '2 pm', 'Physics'), ('Tue', '11 am', 'Maths')]
k = 3
res = 1
for t in listA:
    if len(t) != k:
        res = 0
        break
print("Each tuple has same length" if res else "All tuples are not of same length")

วิธี 2: ใช้ all() กับ Generator Expression

listA = [('Mon', '2 pm', 'Physics'), ('Tue', '11 am', 'Maths')]
k = 3
res = all(len(t) == k for t in listA)
print("Each tuple has same length" if res else "All tuples are not of same length")

สรุป

วิธี 2 เป็น Pythonic กว่า ใช้ all() หยุดทันทีเมื่อเจอ False (Short-circuit) โค้ดกระชับ อ่านง่าย