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

Python - Gom nhóm chuỗi theo độ dài K sử dụng hậu tố (suffix)


Gom nhóm các chuỗi trong danh sách dựa trên hậu tố (suffix) có độ dài K. Sử dụng dictionary và khối try-except để tích lũy.

Ví dụ

Minh họa:

my_list = ['peek', "leak", 'creek', "weak", "good", 'week', "wood", "sneek"]
print("Danh sách:", my_list)
K = 3
print("Giá trị K:", K)
my_result = {}
for element in my_list:
    suff = element[-K:]
    try:
        my_result[suff].append(element)
    except:
        my_result[suff] = [element]
print("Kết quả gom nhóm:", my_result)

Kết quả

Danh sách: ['peek', 'leak', 'creek', 'weak', 'good', 'week', 'wood', 'sneek']
Giá trị K: 3
Kết quả gom nhóm: {'ood': ['good', 'wood'], 'eak': ['leak', 'weak'], 'eek': ['peek', 'creek', 'week', 'sneek']}

Giải thích

  • Khởi tạo dictionary rỗng.
  • Duyệt từng chuỗi, lấy hậu tố K ký tự cuối (element[-K:]).
  • Thử append vào list tại key suffix; nếu key chưa tồn tại (KeyError), except tạo mới list chứa chuỗi đó.