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

Python – Extract Strings ที่มี Character จากชุดที่กำหนด มากกว่าหรือเท่ากับ K ตัว

ภาพรวม

จาก list ของสตริง ให้คัดเฉพาะสตริงที่มีตัวอักษรจาก char_list จำนวน >= key ตัว

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


my_list = ["Python", "is", "fun", "to", "learn"]
my_char_list = ['e', 't', 's', 'm', 'n']
my_key = 2

print("The list is:", my_list)
print("The value of key is:", my_key)

my_result = [
    s for s in my_list
    if sum(ch in my_char_list for ch in s) >= my_key
]

print("The resultant list is:", my_result)

ผลลัพธ์

The list is: ['Python', 'is', 'fun', 'to', 'learn']
The value of key is: 2
The resultant list is: ['Python', 'learn']

คำอธิบาย

StringChars in setCount>=2?
Pythont, n2✓
iss1✗
funn1✗
tot1✗
learne, a, r, n (e,n ใน set)2✓

Case Insensitive Version


char_set = set(c.lower() for c in my_char_list)
my_result = [
    s for s in my_list
    if sum(ch.lower() in char_set for ch in s) >= my_key
]

ประยุกต์ใช้

  • Filter คำที่มี vowel มากพอ
  • Spell check: คำที่มีตัวอักษรผิดปกติ
  • Password policy: ต้องมี special chars จำนวนหนึ่ง