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

ลบ Empty Tuples ออกจาก List ใน Python

บทนำ

การลบ tuple ว่าง (()) และค่าที่ถือว่า "ว่าง" ออกจากลิสต์ สามารถทำได้ด้วย list comprehension กรองเฉพาะค่าที่เป็น Truthy

ตัวอย่างโค้ด

def remove_empty_tuples(lst):
    """ลบ tuple ว่างและค่า falsy อื่นๆ"""
    return [item for item in lst if item]

# ข้อมูลทดสอบ: มี tuple ว่าง, string ว่าง, tuple ของ space, tuple ปกติ, string
data = [(), (), '', (' ', ' '), (45, 67, 35, 66, 74, 89, 100), 'jane']
print("ข้อมูลเดิม:", data)

cleaned = remove_empty_tuples(data)
print("หลังลบค่าว่าง:", cleaned)

ผลลัพธ์

ข้อมูลเดิม: [(), (), '', (' ', ' '), (45, 67, 35, 66, 74, 89, 100), 'jane']
หลังลบค่าว่าง: [(' ', ' '), (45, 67, 35, 66, 74, 89, 100), 'jane']

คำอธิบาย

  • if item กรองเฉพาะค่าที่เป็น Truthy
  • ใน Python ค่า Falsy ได้แก่: (), [], {}, '', 0, None, False
  • (' ', ' ') ไม่ใช่ tuple ว่าง (มี element คือ space) จึงไม่ถูกลบ

กรองเฉพาะ Tuple ว่าง (ไม่ลบ string ว่าง)

def remove_only_empty_tuples(lst):
    return [item for item in lst if not (isinstance(item, tuple) and len(item) == 0)]

# ทดสอบ
print(remove_only_empty_tuples(data))
# [('', (' ', ' '), (45, 67, 35, 66, 74, 89, 100), 'jane']