นับจำนวน List ที่เป็น Element ของ Tuple
Tuple ใน Python สามารถมี List เป็นสมาชิกได้ ต้องการนับจำนวน List ภายใน Tuple
วิธีที่ 1: ใช้ len() โดยตรง
ถ้า Tuple ประกอบด้วย List เท่านั้น len(tuple) ให้จำนวน List ทันที
tupA = (['a','b','x'], [21,19])
tupB = (['n','m'], ['z','y','x'], [3,7,89])
print(len(tupA)) # 2
print(len(tupB)) # 3
วิธีที่ 2: ใช้ User-defined Function (ตรวจสอบประเภท)
def getcount(tupl):
if isinstance(tupl, tuple):
return len(tupl)
return 0
print(getcount(tupA)) # 2
print(getcount(tupB)) # 3