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

แทนที่ค่าซ้ำใน Tuple ด้วยค่าที่กำหนดใน Python

บทนำ

การแทนที่ element ที่ซ้ำกันใน tuple (เก็บแค่ครั้งแรก ค่าถัดไปแทนที่ด้วยค่าที่กำหนด เช่น 'FILL') สามารถทำได้โดยใช้ set ติดตามค่าที่เจอแล้ว ร่วมกับ generator expression

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

my_tuple = (11, 14, 0, 78, 33, 11, 10, 78, 0)
print("Tuple เดิม:", my_tuple)

seen = set()
FILL_VALUE = 'FILL'

# สร้าง tuple ใหม่: เก็บค่าเดิมถ้ายังไม่เจอ, แทนที่ด้วย FILL ถ้าเจอแล้ว
result = tuple(val if val not in seen and not seen.add(val) else FILL_VALUE 
               for val in my_tuple)

print("หลังแทนที่ค่าซ้ำ:", result)

ผลลัพธ์

Tuple เดิม: (11, 14, 0, 78, 33, 11, 10, 78, 0)
หลังแทนที่ค่าซ้ำ: (11, 14, 0, 78, 33, 'FILL', 10, 'FILL', 'FILL')

คำอธิบาย

  • val not in seen ตรวจสอบว่าเจอค่านี้แล้วหรือยัง
  • not seen.add(val) เพิ่มค่าเข้า set (คืน None → False → not False = True) ทำให้เงื่อนไขแรกเป็น True สำหรับค่าใหม่
  • ถ้าเจอแล้ว (val in seen เป็น True) → ข้ามเงื่อนไขแรก → ใช้ else FILL_VALUE

วิธีเข้าใจง่ายกว่า (ใช้ลูป)

seen = set()
result = []
for val in my_tuple:
    if val in seen:
        result.append(FILL_VALUE)
    else:
        seen.add(val)
        result.append(val)
result = tuple(result)
print(result)