Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python – Tách chuỗi theo tiền tố (Prefix Occurrence)

Khi cần tách list chuỗi thành các nhóm dựa trên sự xuất hiện của tiền tố (prefix), ta dùng zip_longest từ itertools.

Ví dụ

from itertools import zip_longest

my_list = ["hi", 'hello', 'there', "python", "object", "oriented", "object", "cool", "language", 'py', 'extension', 'bjarne']
print("Danh sách:")
print(my_list)

my_prefix = "python"
print("Tiền tố:", my_prefix)

my_result, my_temp_val = [], []

for x, y in zip_longest(my_list, my_list[1:]):
    my_temp_val.append(x)
    if y and y.startswith(my_prefix):
        my_result.append(my_temp_val)
        my_temp_val = []

my_result.append(my_temp_val)

print("Kết quả tách:")
print(my_result)

print("Sau khi sắp xếp:")
my_result.sort()
print(my_result)

Kết quả đầu ra

Danh sách:
['hi', 'hello', 'there', 'python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension', 'bjarne']
Tiền tố: python
Kết quả tách:
[['hi', 'hello', 'there'], ['python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension', 'bjarne']]
Sau khi sắp xếp:
[['hi', 'hello', 'there'], ['python', 'object', 'oriented', 'object', 'cool', 'language', 'py', 'extension', 'bjarne']]

Giải thích

  • zip_longest(my_list, my_list[1:]) tạo cặp (phần tử hiện tại, phần tử tiếp theo).
  • Tích lũy vào my_temp_val cho đến khi phần tử tiếp theo bắt đầu bằng prefix.
  • Khi gặp prefix ở phần tử tiếp theo: đẩy nhóm hiện tại vào kết quả, reset temp.
  • Cuối cùng thêm nhóm còn lại.

Ý nghĩa: Phân đoạn list tại ranh giới từ khóa/prefix.