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

Python – Selective Consecutive Suffix Join (รวมสตริงต่อเนื่องที่ลงท้ายด้วย Suffix)

ภาพรวม

รวมสตริงใน list ต่อเนื่องกันจนกว่าจะเจอสตริงที่ ไม่ลงท้าย ด้วย suffix ที่กำหนด (เช่น '-')

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


my_list = ["Python-", "fun", "to-", "code"]
suffix = '-'
print("The list is:", my_list)
print("The suffix is:", suffix)

result = []
temp = []

for element in my_list:
    temp.append(element)
    if not element.endswith(suffix):
        result.append(''.join(temp))
        temp = []

print("The result is:", result)

ผลลัพธ์

The list is: ['Python-', 'fun', 'to-', 'code']
The suffix is: -
The result is: ['Python-fun', 'to-code']

คำอธิบาย

  • "Python-" ลงท้าย '-' -> เก็บไว้ใน temp
  • "fun" ไม่ลงท้าย '-' -> join temp + "fun" = "Python-fun" -> เพิ่มใน result, clear temp
  • "to-" ลงท้าย '-' -> เก็บใน temp
  • "code" ไม่ลงท้าย '-' -> join = "to-code" -> เพิ่มใน result

กรณีขอบ (Edge Cases)


# List จบด้วย suffix -> temp เหลือไม่ถูก flush
my_list = ["a-", "b-", "c"]
# ผล: ["a-b-"]  (c ไม่ได้รวมเพราะไม่มี non-suffix ต่อท้าย)

# แก้: flush temp หลังลูป
if temp:
    result.append(''.join(temp))

ประยุกต์ใช้

  • Parse command line arguments ที่แยกด้วย flag
  • รวม token ที่แยกโดย delimiter
  • ประมวลผล log lines ที่ continuation ด้วย \ หรือ -