ภาพรวม
เมื่อต้องการแยก Tuple ที่มีจำนวนองค์ประกอบเฉพาะ สามารถใช้ List Comprehension วนลูปผ่านองค์ประกอบของ List of Tuple และตั้งเงื่อนไขที่ต้องปฏิบัติ จะกรององค์ประกอบเฉพาะและเก็บในตัวแปรอื่น
ตัวอย่างโค้ด
my_list = [(34, 56), (45, 6), (111, 90), (11, 35), (78, )]
print("The list is : ")
print(my_list)
K = 2
print("The value of K has been initialized to" + "str(K)")
my_result = [sub for sub in my_list if all(len(str(elem)) == K for elem in sub)]
print("The tuples extracted are : ")
print(my_result)
ผลลัพธ์ตัวอย่าง
The list is : [(34, 56), (45, 6), (111, 90), (11, 35), (78,)] The value of K has been initialized tostr(K) The tuples extracted are : [(34, 56), (11, 35), (78,)]
คำอธิบาย
- นิยาม List of Tuple และแสดงบนคอนโซล
- กำหนดค่า
K - ใช้ List Comprehension วนลูปผ่าน List of Tuple
- ตรวจสอบว่า Tuple ทุกตัวใน List มีขนาดเท่ากัน
- แปลงเป็น List และกำหนดให้ตัวแปร
- แสดงผลลัพธ์บนคอนโซล