เมื่อต้องการกรองลิสต์ของทัพเพิล ให้เหลือเฉพาะทัพเพิลที่ความยาวไม่เท่ากับ K สามารถใช้ List Comprehension กับเงื่อนไข len(ele) != K
ตัวอย่างโค้ด
my_list = [(32, 51), (22, 13), (94, 65, 77), (70,), (80, 61, 13, 17)]
print("The list is:")
print(my_list)
K = 1
print("The value of K is:", K)
filtered = [ele for ele in my_list if len(ele) != K]
print("The filtered list is:")
print(filtered)ผลลัพธ์
The list is: [(32, 51), (22, 13), (94, 65, 77), (70,), (80, 61, 13, 17)] The value of K is: 1 The filtered list is: [(32, 51), (22, 13), (94, 65, 77), (80, 61, 13, 17)]
คำอธิบาย
กำหนดลิสต์ทัพเพิลที่มีความยาวต่างกัน
ตั้งค่า K = 1 (ต้องการลบทัพเพิลที่มี 1 องค์ประกอบ)
ใช้ List Comprehension กรองเฉพาะทัพเพิลที่
len(ele) != Kทัพเพิล (70,) ถูกลบออก เพราะมีความยาว 1