ในบทความนี้ เราจะมาดูกันว่าสิ่งอันดับทั้งหมดในรายการที่กำหนดมีความยาวเท่ากันหรือไม่
มีเลน
เราจะใช้ฟังก์ชัน len และเปรียบเทียบผลลัพธ์กับค่าที่กำหนดซึ่งเรากำลังตรวจสอบ หากค่าเท่ากัน เราจะถือว่าค่าเหล่านั้นมีความยาวไม่เท่ากัน
ตัวอย่าง
listA = [('Mon', '2 pm', 'Physics'), ('Tue', '11 am','Maths')]
# printing
print("Given list of tuples:\n", listA)
# check length
k = 3
res = 1
# Iteration
for tuple in listA:
if len(tuple) != k:
res = 0
break
# Checking if res is true
if res:
print("Each tuple has same length")
else:
print("All tuples are not of same length") ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given list of tuples:
[('Mon', '2 pm', 'Physics'), ('Tue', '11 am', 'Maths')]
Each tuple has same length ด้วยทั้งหมดและเลน
เราฟ้องฟังก์ชัน len ที่สอดคล้องกับฟังก์ชัน all และใช้ a for loop เพื่อวนซ้ำผ่านแต่ละ tuple ที่อยู่ในรายการ
ตัวอย่าง
listA = [('Mon', '2 pm', 'Physics'), ('Tue', '11 am','Maths')]
# printing
print("Given list of tuples:\n", listA)
# check length
k = 3
res=(all(len(elem) == k for elem in listA))
# Checking if res is true
if res:
print("Each tuple has same length")
else:
print("All tuples are not of same length") ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given list of tuples:
[('Mon', '2 pm', 'Physics'), ('Tue', '11 am', 'Maths')]
Each tuple has same length