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

แยกสตริงตาม Prefix Occurrence (Split Strings on Prefix)

แนวคิด

จากลิสต์สตริง ให้แยกเป็นกลุ่มย่อย (sublists) ทุกครั้งที่เจอสตริงที่ขึ้นต้นด้วย prefix ที่กำหนด ใช้ itertools.zip_longest เปรียบเทียบปัจจุบันกับถัดไป

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

from itertools import zip_longest

my_list = ["hi", "hello", "there", "python", "object", "oriented", "object", "cool", "language", "py", "extension", "bjarne"]
print("ลิสต์:", my_list)

my_prefix = "python"
print("Prefix:", my_prefix)

result, temp = [], []
for current, next_item in zip_longest(my_list, my_list[1:]):
    temp.append(current)
    if next_item and next_item.startswith(my_prefix):
        result.append(temp)
        temp = []
result.append(temp)  # กลุ่มสุดท้าย

print("กลุ่มหลังแยก:", result)

ผลลัพธ์

ลิสต์: ['hi', 'hello', 'there', 'python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension', 'bjarne']
Prefix: python
กลุ่มหลังแยก: [['hi', 'hello', 'there'], ['python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension', 'bjarne']]

คำอธิบาย

  • zip_longest(list, list[1:]) จับคู่ (current, next) สำหรับทุกตำแหน่ง
  • สะสม current เข้า temp
  • ถ้า next_item เริ่มต้นด้วย prefix -> ปิดกลุ่ม temp, เริ่มกลุ่มใหม่
  • หลังลูป ต้อง append temp ที่เหลือ

วิธีง่ายกว่า (ไม่ใช้ zip_longest)

result = []
current_group = []
for item in my_list:
    if item.startswith(my_prefix) and current_group:
        result.append(current_group)
        current_group = []
    current_group.append(item)
if current_group:
    result.append(current_group)