我試圖找出哪些詞適合此模板,但不知道如何比較它們。有沒有什么方法可以做到這一點而不計算模板中的特定字母字符,獲取它們的索引,然后檢查每個單詞中的每個字母?
所需的輸出是符合模板的單詞串列。
alist = []
template = ['_', '_', 'l', '_', '_']
words = ['hello', 'jacky', 'helps']
if (word fits template):
alist.append(word)
uj5u.com熱心網友回復:
您可以使用zip將單詞與模板進行比較:
def word_fits(word, template):
if len(word) != len(template):
return False
for w, t in zip(word, template):
if t != "_" and w != t:
return False
return True
template = ["_", "_", "l", "_", "_"]
words = ["hello", "jacky", "helps"]
alist = [w for w in words if word_fits(w, template)]
print(alist)
印刷:
["hello", "helps"]
uj5u.com熱心網友回復:
您可以使用正則運算式(將模板轉換為正則運算式,然后獲取所有匹配的詞):
import re
template = ['_', '_', 'l', '_', '_']
words = ['hello', 'jacky', 'helps']
regexp = ''.join(template).replace('_','.')
# '..l..' in this case
match_words = [word for word in words if re.match(regexp,word)]
match_words
# Out[108]: ['hello', 'helps']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/537550.html
