比较不同列表中的项目

问题描述:

我有一个函数是hangman的一部分,它有两个输入

I have a function that is a part of hangman, that gets two inputs

filter_words_list(words, pattern):

我需要一种方法来知道单词中的字母与特定位置的单词是相同的 到图案中的字母(未发现)的位置,并且这些字母位于同一位置. 而且,单词和图案应该长度相同

I need a way to know that the letter in a word from the words in a specific spot, is identical to the letter (that is uncovered) in the pattern and that those letters are IN THE SAME PLACE. also, word and pattern ought to be in the same length

这是香港专业教育学院的尝试:

this is what ive tried:

def filter_words_list(words, pattern):
    relevant_words = []
    for word in words:
        if len(word) == len(pattern):
            for i in range(len(word)):
                for j in range(len(pattern)):
                    if word[i] == pattern[j] and i == j:
                        relevant_words.append(word)
print(relevant_words)

filter_words_list(['aardvark', 'aardwolf', 'aaron', 'aback', 'abacus', 
'abaft', 'abalone'],'ab___',))

打印:不好..您可以在这里看到:

print: not good.. as you can see here:

['aaron', 'aback', 'aback', 'abaft', 'abaft']

我需要的照片:

['aback', 'abaft']

谢谢!

如果您使用.而不是_来表示丢失的字符,则基本上可以得到一个正则表达式,例如:

If you use . instead of _ for your missing character then you've basically got a regular expression, eg:

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...