[英]While loop: list index out of range
I've been making a function to search through two lists and check if a character is in both lists.The error我一直在制作一个函数来搜索两个列表并检查两个列表中是否有一个字符。错误
"IndexError: list index out of range"
“索引错误:列表索引超出范围”
keeps coming up.不断出现。 I put this through python Tutor and it seems like the while loop is totally ignored.I'm coding this search without using the in function in an if statement .
我通过 python Tutor 提交了这个,似乎 while 循环被完全忽略了。我正在编码这个搜索,而没有在 if 语句中使用 in 函数。 Any help would be much appreciated!
任何帮助将不胜感激!
Here is my code:这是我的代码:
aList = ["B" , "S" , "N" , "O" , "E" , "U" , "T" ]
userInput = "TOE"
userInputList = list(userInput)
letterExists = 0
while (letterExists < len(userInput)):
for i in aList:
if (i == userInputList[letterExists]):
letterExists +=1
if (letterExists == len(userInput)):
print("This word can be made using your tiles")
letterExists < len(userInput)
only guarantees that there is 1 more letter that can be processed, but you may iterate more than 1 time by means of the for
loop. letterExists < len(userInput)
仅保证还有 1 个可以处理的字母,但您可以通过for
循环迭代 1 次以上。
By the way, you can write this condition very nicely using set
:顺便说一句,您可以使用
set
非常好地编写此条件:
the_set = set(["B", "S", ...])
if(all(x in the_set for x in userInput)):
...
你可以使用 python magic 并像这样写:
len([chr for chr in userInput if chr in aList]) == len(userInput)
Looking at your code and without trying to do better, I found that a break
is missing after the incrementation of letterExists
.看你的代码,并没有试图做的更好,我发现一个
break
是的递增后失踪letterExists
。 Here is the fixed code:这是固定代码:
aList = ["B" , "S" , "N" , "O" , "E" , "U" , "T" ]
userInput = "TOE"
userInputList = list(userInput)
letterExists = 0
while (letterExists < len(userInput)):
for i in aList:
if (i == userInputList[letterExists]):
letterExists +=1
break
if (letterExists == len(userInput)):
print("This word can be made using your tiles")
However, a better pythonic solution is the following (same as xtofl 's answer):但是,更好的pythonic解决方案如下(与xtofl的答案相同):
aList = ["B" , "S" , "N" , "O" , "E" , "U" , "T" ]
userInput = "TOF"
a = all([letter in aList for letter in userInput])
if (a):
print("This word can be made using your tiles")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.