在完成所有列表元素之前,Python循环会停止迭代(不抛出错误)是什么原因?

2024-10-02 06:23:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个Python程序,它可以查看用户输入的单词的所有字母是否在列表中的其他单词中找到。因此,例如,如果用户输入“孟菲斯”,程序应该打印一个包含所有相同字母的单词列表(例如“委婉语”、“成员资格”、“油印本”)。在

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)

问题是,在一大串单词中,没有一个单词没有通过测试。即使应该失败的单词也会被附加到匹配列表中。所以,当我输入“孟菲斯”与大列表进行比较时,列表中的每个单词都会被打印出来。在

有什么想法吗?提前谢谢。在


Tags: oftoin程序列表for单词list
3条回答

我会把它作为

filter(set(userWord).issubset, wordList)

示例:

^{pr2}$

Any reason a Python loop would stop iterating (without throwing errors) before finishing all list elements?

不,但是在您的特定示例中,您在迭代iterable userLetters.remove(letter)时更改它的大小for letter in userLetters:

在Python中,行为定义得很好,因此在迭代时会跳过元素。在

或者,您应该创建正在迭代的iterable的副本for letter in userLetters[:]:

你不应该从你正在浏览的列表中删除项目。复制列表,例如使用[:]

...
for letter in userLetters[:]:
    if letter in wordLetters:
...

相关问题 更多 >

    热门问题