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

ลบ Tuple ที่มีสมาชิกเป็น None ทุกตัวออกจาก List ใน Python

เมื่อต้องการลบ tuple ที่มีสมาชิกเป็น None ทุกตัวออกจาก list of tuples สามารถใช้ list comprehension ร่วมกับ all()

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

my_list = [(2, None, 12), (None, None, None), (23, 64), (121, 13), (None,), (None, 45, 6)]
print("The list is:")
print(my_list)
my_result = [sub for sub in my_list if not all(elem is None for elem in sub)]
print("The None tuples have been removed, the result is:")
print(my_result)

ผลลัพธ์

The list is: [(2, None, 12), (None, None, None), (23, 64), (121, 13), (None,), (None, 45, 6)]
The None tuples have been removed, the result is: [(2, None, 12), (23, 64), (121, 13), (None, 45, 6)]

คำอธิบาย

  • กำหนด list of tuples ที่มี tuple บางตัวประกอบด้วย None ทั้งหมด

  • ใช้ list comprehension: [sub for sub in my_list if not all(elem is None for elem in sub)]

  • all(elem is None for elem in sub) คืน True ก็ต่อเมื่อทุก elem ใน sub เป็น None

  • not all(...) หมายถึง "ไม่ใช่ tuple ที่เป็น None ทั้งหมด" → เก็บไว้

  • Tuple (2, None, 12) และ (None, 45, 6) ไม่ถูกลบ เพราะมีสมาชิกที่ไม่ใช่ None

ข้อสังเกต: ใช้ elem is None แทน elem == None เป็น best practice ใน Python (identity check เร็วกว่าและปลอดภัยกว่า)