gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:37:23 26 4
gpt4 key购买 nike

我正在编写一个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”与大列表进行比较时,列表中的每个单词都会被打印出来。

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

最佳答案

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

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

在 Python 中,行为是明确定义的,您最终会在迭代时跳过元素。

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

关于python - Python 循环在完成所有列表元素之前停止迭代(不抛出错误)有什么原因吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15608762/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com