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

代码男孩

该代码的目标是找到给定句子中存在的“ 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):

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在以下布局中访问属性时出现“列表索引超出范围”错误

为什么我的列表中出现字符串超出范围索引错误?

Python错误:列表索引超出范围

For循环错误:列表索引超出范围

Scrapy错误。列表索引超出范围

列表索引超出范围... :(

在Python的while循环中追加列表会出现错误消息“列表索引超出范围”

为什么会出现错误:列表索引超出范围

显示最近创建的空表时在HIVE中出现“错误:列表索引超出范围”

为什么为什么不断出现错误“ IndexError:列表索引超出范围”?

嵌套循环结构中出现“列表索引超出范围”错误,但不在此范围之外

为什么在创建类的实例时出现“列表索引超出范围”错误?

列表索引超出范围

列表索引超出范围

列表-索引超出范围

运行节俭示例时出现“ IndexError:列表索引超出范围”错误

如果出现错误“ IndexError:列表索引超出范围”,请重新加载页面

列表索引超出范围错误-熊猫

列表索引超出范围

列表索引超出范围

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

Python读取XML文件不断出现错误“列表索引超出范围”

Python字典索引错误:列表索引超出范围

运行 Poetry install 命令出现错误:列表索引超出范围

为什么“列表索引超出范围”错误仅在我输入 10 时出现?

Python 列表列表为什么会出现此错误:IndexError:列表索引超出范围?

索引错误:列表索引超出范围:

python随机索引错误:列表索引超出范围

使用 Pandas 和 Yahoo_fin 时出现列表索引超出范围错误