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

ลบ Tuple ออกจากลิสต์ของ Tuple หากไม่มีตัวอักษรใน Python


เมื่อต้องการลบ Tuple จากลิสต์ของ Tuple ตามเงื่อนไขที่กำหนด คือ Tuple ไม่มีตัวอักษรเฉพาะ สามารถใช้ list comprehension ได้

ลิสต์สามารถเก็บค่าที่หลากหลายได้ ลิสต์ของ Tuple คือ Tuple ที่อยู่ภายในลิสต์

List comprehension เป็นวิธีเขียนสั้นๆ สำหรับวนลูปผ่านลิสต์และดำเนินการ

ตัวอย่าง

my_list = [('. ', 62), ('Mark', 5), ('Paul.', 21), ('.....', 0), ('-Jane', 115), ('Jake', 15), ('::', 63), ('John', 3), ('--', 1), ('there', 82), ('Harold', 100)]
my_result = [(a, b) for a, b in my_list if any(c.isalpha() for c in a)]
print("The tuple that doesn't contain any character has been removed")
print("The resultant list of tuple is :")
print(my_result)

ผลลัพธ์

The tuple that doesn't contain any character has been removed
The resultant list of tuple is : [('Mark', 5), ('Paul.', 21), ('-Jane', 115), ('Jake', 15), ('John', 3), ('there', 82), ('Harold', 100)]

คำอธิบาย

  • กำหนดลิสต์ของ Tuple และแสดงบนคอนโซล
  • วนลูปลิสต์ของ Tuple และตรวจสอบว่ามีตัวอักษรหรือไม่
  • ข้อมูลจากการดำเนินการนี้ถูกเก็บในตัวแปร
  • ตัวแปรนี้คือเอาต์พุทที่แสดงบนคอนโซล