我一直在做一个函数来搜索两个列表,并检查两个列表中是否都有一个字符列表错误
"IndexError: list index out of range"
不断地出现。我通过python Tutor实现了这一点,似乎while循环被完全忽略了,我编写这个搜索时没有在if语句中使用in函数。任何帮助都将不胜感激!你知道吗
这是我的密码:
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)
只保证还有1个字母可以处理,但是您可以通过for
循环重复1次以上。你知道吗顺便说一下,您可以使用
set
很好地编写这个条件:在查看您的代码时,没有尝试做得更好,我发现在增量
letterExists
之后缺少break
。以下是固定代码:然而,一个更好的pythonic解决方案如下(与xtofl的答案相同):
您可以使用python magic并这样编写:
相关问题 更多 >
编程相关推荐