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

วิธีดึงเอลีเมนต์ที่ไม่ซ้ำกันจาก Nested Tuple ใน Python

การหาค่าที่ไม่ซ้ำกัน (Unique Elements) ใน Nested Tuple

เมื่อต้องการดึงเอลีเมนต์ที่ไม่ซ้ำกันจาก Nested Tuple (Tuple ที่มี Tuple อื่นๆ อยู่ข้างใน) สามารถใช้ Nested Loop ร่วมกับ Set ได้

ข้อดีของ Set

Python มีข้อมูลชนิด set ซึ่งเก็บเฉพาะค่าที่ไม่ซ้ำกัน (Unique) เท่านั้น Set ยังมีประโยชน์ในการทำ operation ต่างๆ เช่น intersection, difference, union, และ symmetric difference

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

my_list_1 = [(7, 8, 0), (0, 3, 45), (3, 2, 22), (45, 12, 9)]
print("The list of tuple is : ")
print(my_list_1)

my_result = []
temp = set()

for inner in my_list_1:
    for elem in inner:
        if elem not in temp:
            temp.add(elem)
            my_result.append(elem)

print("The unique elements in the list of tuples are : ")
print(my_result)

ผลลัพธ์

The list of tuple is : [(7, 8, 0), (0, 3, 45), (3, 2, 22), (45, 12, 9)]
The unique elements in the list of tuples are : [7, 8, 0, 3, 45, 2, 22, 12, 9]

คำอธิบาย

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

เทคนิคเพิ่มเติม

สามารถทำได้สั้นกว่าด้วย set โดยตรง:

# วิธีสั้นๆ
unique_elements = list(set(elem for inner in my_list_1 for elem in inner))
print(unique_elements)
# ผลลัพธ์: [0, 2, 3, 7, 8, 9, 12, 22, 45] (ลำดับอาจต่างไปตามลักษณะของ set)