ภาพรวม
จาก 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']
คำอธิบาย
| String | Chars in set | Count | >=2? |
|---|---|---|---|
| Python | t, n | 2 | ✓ |
| is | s | 1 | ✗ |
| fun | n | 1 | ✗ |
| to | t | 1 | ✗ |
| learn | e, 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 จำนวนหนึ่ง