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

ลบ Tuple ที่ตรงกันใน Python


เมื่อต้องการลบ Tuple ที่ตรงกันจากสองลิสต์ของ Tuple สามารถใช้ list comprehension ได้

ลิสต์สามารถเก็บค่าที่หลากหลายได้

ลิสต์ของ Tuple คือ Tuple ที่อยู่ภายในลิสต์

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

ตัวอย่าง

my_list_1 = [('Hi', 'there'), ('Jane', 'Hi'), ('how', 'are'), ('you', '!')]
my_list_2 = [('Hi', 'there'), ('Hi', 'Jane')]
print("The first list is : ")
print(my_list_1)
print("The second list is : ")
print(my_list_2)
my_result = [sub for sub in my_list_1 if sub not in my_list_2]
print("The filtered out list of tuples is : ")
print(my_result)

ผลลัพธ์

The first list is : [('Hi', 'there'), ('Jane', 'Hi'), ('how', 'are'), ('you', '!')]
The second list is : [('Hi', 'there'), ('Hi', 'Jane')]
The filtered out list of tuples is : [('Jane', 'Hi'), ('how', 'are'), ('you', '!')]

คำอธิบาย

  • กำหนดสองลิสต์ของ Tuple และแสดงบนคอนโซล
  • ใช้ list comprehension วนลูปผ่าน Tuple
  • จะกรอง Tuple ที่อยู่ในทั้งสองลิสต์ออก
  • Tuple ที่เหลือจะแสดงบนคอนโซล