获取“列表索引超出范围”错误

2024-06-25 23:15:38 发布

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

这段代码的目标是找出任何给定句子中的“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))

非常感谢您的帮助。多谢各位


Tags: 函数代码目标列表数量ifshch
3条回答

改为使用范围为的for循环:

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]'''
for i in range(1,len(slist)):
    if slist[i-1] + slist[i] == "sh":
        sh += 1
    elif slist[i-1] + slist[i] == "ch":
        ch += 1
    elif slist[i-1] + slist[i] == "th":
        th += 1
    elif slist[i-1] + slist[i] == "wh":
        wh += 1

print(f"Has {ch} 'ch' {sh} 'sh' {th} 'th' {wh} 'wh'")

从1开始,检查i-1和i,这样你就不会超出索引范围

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

while i < len(slist) - 1:

作为旁注,for在这里似乎更合适。删除i = 0i+=1

for i in range(len(slist) - 1):

您正在检查当前位置之前的一个位置。因此,您会得到超出范围的错误

基本上,迭代数组的每个位置,但检查第n个位置和第n+1个位置。当你到达最后一个位置时会发生什么?您使用未定义的下一个位置检查它(否则它将不是最后一个位置),从而得到超出范围的错误

我的建议是不要对最后一项和下一项进行检查,因为不再有任何顺序

while i < len(slist) - 1:
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

相关问题 更多 >