这段代码的目标是找出任何给定句子中的“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))
非常感谢您的帮助。多谢各位
改为使用范围为的for循环:
从1开始,检查i-1和i,这样你就不会超出索引范围
i+1
将超出slist
范围。您需要迭代到slist
size-1作为旁注,
for
在这里似乎更合适。删除i = 0
和i+=1
您正在检查当前位置之前的一个位置。因此,您会得到超出范围的错误
基本上,迭代数组的每个位置,但检查第n个位置和第n+1个位置。当你到达最后一个位置时会发生什么?您使用未定义的下一个位置检查它(否则它将不是最后一个位置),从而得到超出范围的错误
我的建议是不要对最后一项和下一项进行检查,因为不再有任何顺序
相关问题 更多 >
编程相关推荐