3 回答
TA贡献1818条经验 获得超7个赞
这样的事情可能会奏效:
words = ('aardvark', 'aardwolf', 'aaron', 'aback', 'abacus',
'abaft', 'abalone')
pattern = 'ab___'
def match(word, pattern):
# also need to match the length?
# if len(word) != len(pattern):
# return False
for letter, p in zip(word, pattern):
if p == '_':
continue
if letter != p:
return False
return True
matches = [word for word in words if match(word, pattern)]
print(matches)
它将单词的一个字母与模式的一个字符进行比较(使用zip以遍历这些对)。如果模式的字符是 ,它会忽略'_'。
现在编写函数时,它不考虑单词或模式的长度。
TA贡献1804条经验 获得超7个赞
如果你使用.而不是_你丢失的字符,那么你基本上有一个正则表达式,例如:
import re
words = ['aardvark', 'aardwolf', 'aaron', 'aback', 'abacus', 'abaft', 'abalone']
# starting with ab followed by exactly 3 characters ($ means match end of string)
wanted = [word for word in words if re.match('ab...$')]
# ['aback', 'abaft']
# starting with ab followed by at least 3 characters (notice no $ here)
wanted2 = [word for word in words if re.match('ab...', word)]
# ['aback', 'abacus', 'abaft', 'abalone']
# starting with ab, followed by any letter, followed by "f", and exactly one letter
wanted3 = [word for word in words if re.match('ab.f.$', word)]
# ['abaft']
# etc...
TA贡献1817条经验 获得超6个赞
检查以下代码:
def filter_words_list(words, pattern):
relevant_words = []
pat = pattern.replace("_","")
for word in words:
if word.startswith(pat):
relevant_words.append(word)
print(relevant_words)
filter_words_list(['aardvark', 'aardwolf', 'aaron', 'aback', 'abacus','abaft', 'abalone'],'ab___',)
输出:
['aback', 'abacus', 'abaft', 'abalone']
注意:它仅在给出模式的情况下起作用,例如它以某些字符开头。例如,如果模式是“__a_”,它就不会起作用。如果您需要类似的东西,请编辑您的问题。
添加回答
举报