While循环:列表索引超出范围

2024-10-01 00:15:58 发布

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

我一直在做一个函数来搜索两个列表,并检查两个列表中是否都有一个字符列表错误

"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")

Tags: 函数in列表indexlenif错误字符
3条回答

letterExists < len(userInput)只保证还有1个字母可以处理,但是您可以通过for循环重复1次以上。你知道吗

顺便说一下,您可以使用set很好地编写这个条件:

the_set = set(["B", "S", ...])
if(all(x in the_set for x in userInput)):
   ...

在查看您的代码时,没有尝试做得更好,我发现在增量letterExists之后缺少break。以下是固定代码:

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")

然而,一个更好的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")

您可以使用python magic并这样编写:

len([chr for chr in userInput if chr in aList]) == len(userInput)

相关问题 更多 >