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

Python: หาสตริงที่เป็น Substring ของลิสต์สตริงอีกชุดหนึ่ง

บทนำ

เมื่อต้องการหาสตริงที่ปรากฏเป็น substring (ส่วนย่อย) ในลิสต์สตริงอีกชุดหนึ่ง สามารถใช้ set comprehension ร่วมกับการวนลูปซ้อนได้อย่างมีประสิทธิภาพ

หลักการ

  1. วนลูปทุกคู่ของสตริงจากลิสต์ทั้งสอง
  2. ตรวจสอบว่า elem_1 in subset_1 (elem_1 เป็น substring ของ subset_1)
  3. ใช้ set() เพื่อกำจัดค่าซ้ำ
  4. แปลงกลับเป็น list()

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

my_list_1 = ["Hi", "there", "how", "are", "you"]
my_list_2 = ["Hi", "there", "how", "have", "you", "been"]

print("ลิสต์ที่ 1:", my_list_1)
print("ลิสต์ที่ 2:", my_list_2)

# หาสตริงใน list_2 ที่เป็น substring ของสตริงใน list_1
my_result = list(set(
    elem_1 
    for subset_1 in my_list_1 
    for elem_1 in my_list_2 
    if elem_1 in subset_1
))

print("ผลลัพธ์ (substring ที่พบ):", my_result)

ผลลัพธ์

ลิสต์ที่ 1: ['Hi', 'there', 'how', 'are', 'you']
ลิสต์ที่ 2: ['Hi', 'there', 'how', 'have', 'you', 'been']
ผลลัพธ์ (substring ที่พบ): ['there', 'you', 'Hi', 'how']

คำอธิบายโค้ด

# แบบแยกขั้นตอนเพื่อความเข้าใจ
result_set = set()
for subset_1 in my_list_1:      # วนแต่ละคำในลิสต์ 1
    for elem_1 in my_list_2:    # วนแต่ละคำในลิสต์ 2
        if elem_1 in subset_1:  # ถ้าคำในลิสต์ 2 อยู่ในคำของลิสต์ 1
            result_set.add(elem_1)

my_result = list(result_set)

กรณีใช้งานและการขยาย

# 1. หา substring แบบ case-insensitive
result = list(set(
    elem_1.lower() 
    for s1 in my_list_1 
    for elem_1 in my_list_2 
    if elem_1.lower() in s1.lower()
))

# 2. หา substring ที่มีความยาวมากกว่า 2 ตัวอักษร
result = list(set(
    elem_1 
    for s1 in my_list_1 
    for elem_1 in my_list_2 
    if elem_1 in s1 and len(elem_1) > 2
))

# 3. นับจำนวนครั้งที่พบ
from collections import Counter
counts = Counter(
    elem_1 
    for s1 in my_list_1 
    for elem_1 in my_list_2 
    if elem_1 in s1
)
print(counts)  # Counter({'Hi': 1, 'there': 1, 'how': 1, 'you': 1})

ประสิทธิภาพ

  • เวลา: O(n × m × k) โดย n, m = ขนาดลิสต์, k = ความยาวสตริงเฉลี่ย
  • สำหรับข้อมูลใหญ่ ควรพิจารณาใช้ Trie หรือ Aho-Corasick algorithm
  • ใช้ set ลดการตรวจสอบซ้ำได้

สรุป

เทคนิค set comprehension แบบ nested loop เหมาะสำหรับข้อมูลขนาดกลาง ต้องการความเร็วและโค้ดกระชับ สำหรับข้อมูลใหญ่หรือ real-time ควรใช้โครงสร้างข้อมูลเฉพาะทาง