Python循环在未抛出错误情况下停止迭代的原因是什么?
我正在写一个Python程序,这个程序可以检查用户输入的单词的所有字母是否都能在一个单词列表中的其他单词里找到。比如说,如果用户输入“memphis”,那么程序应该打印出一个包含所有相同字母的单词列表(比如“euphemism”,“membership”,“mimeographs”)。
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”去和这个大列表比较时,列表中的每个单词都会被打印出来。
有什么想法吗?提前谢谢你。
3 个回答
0
我会这样来实现它:
filter(set(userWord).issubset, wordList)
举个例子:
>>> filter(set("23").issubset, ["foo", "3foo2"])
['3foo2']
0
在你遍历一个列表的时候,不应该直接删除其中的项目。你可以先复制这个列表,比如用 [:]
这种方式:
...
for letter in userLetters[:]:
if letter in wordLetters:
...
3
有没有什么原因导致Python的循环在没有报错的情况下,提前停止遍历所有列表元素呢?
没有,不过在你这个例子中,你在遍历的时候改变了可迭代对象的大小,具体来说就是用userLetters.remove(letter)
去移除元素,而你是在用for letter in userLetters:
来遍历它。
在Python中,这种行为是有明确规定的,所以你在遍历的时候会跳过一些元素。
另外,你可以创建一个可迭代对象的副本来遍历,比如用for letter in userLetters[:]:
。