该代码的目标是找到给定句子中存在的“sh”,“th”,“wh”和“ch”二字的数量。似乎一切都应该正常运行时,该函数会不断返回“列表索引超出范围”错误。

exsentence = input("Enter a sentence to scan: ")
slist = list(exsentence.lower())
ch = 0
sh = 0
th = 0
wh = 0
i = 0
'''muppets = slist[i] + slist[i+1]'''
while i < len(slist):
    if slist[i] + slist[i+1] == "sh":
        sh += 1
    elif slist[i] + slist[i+1] == "ch":
        ch += 1
    elif slist[i] + slist[i+1] == "th":
        th += 1
    else:
        if slist[i] + slist[i+1] == "wh":
            wh += 1
    i+=1
print("Has {} 'ch' {} 'sh' {} 'th' {} 'wh'".format(ch,sh,th,wh))

任何帮助都是很感激的。谢谢。

最佳答案

i+1将超出slist范围。您需要迭代直到slist大小-1

while i < len(slist) - 1:

附带说明一下,for在这里似乎更合适。删除i = 0i+=1
for i in range(len(slist) - 1):

关于python - 收到 'list index out of range'错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59963392/

10-11 03:31