我正在编写一个 Python 程序,它查看用户输入单词的所有字母是否在列表中的其他单词中找到。因此,例如,如果用户输入“memphis”,程序应该打印包含所有相同字母的单词列表(例如“委婉语”、“会员资格”、“油印机”)。
wordList = ["blah", "blah", "blah"]
userWord = input("Enter a word to compare: ")
userLetters = list(userWord) #Converting user-inputted string to list of chars
matches = [] #Empty list for words that might match later.
for word in wordList:
mismatchCount = 0 #Setting/resetting count of clashes between words
wordLetters = list(word) #Converting word of comparison into list of chars
for letter in userLetters:
if letter in wordLetters:
userLetters.remove(letter) #Removing already-matched letters
wordLetters.remove(letter) #Removing already-matched letters
else:
mismatchCount += 1
if mismatchCount > 0:
continue #Mismatch--abandons word and moves to next
matches.append(word) #If word fails the above IF, it gets added to matches
print(matches)
问题是大单词列表中没有一个单词没有通过测试。即使是应该失败的单词也会被附加到匹配列表中。因此,当我输入“memphis”与大列表进行比较时,列表中的每个单词都会被打印出来。
有任何想法吗?提前致谢。