IndexError 即使索引变量应该在范围内

IndexError even though the index variable should be in range

编辑:将 'hi' 更新为 'list'

我是初学者,我一直致力于将英语句子翻译成 pig latin 的项目,但我在尝试删除句子中标点符号前的空格时遇到了 运行 问题。这是我遇到问题的脚本。

import string

list = ['H', 'i', 's', 't', 'a', 'y', ' ', 's', 'i', 'a', 'y', ' ', 'a', 'a', 'y', ' ', 'e', 's', 't', 't', 'a', 'y', ' ', '.', ' ', 'H', 'i', 's', 't', 'a', 'y', ' ', 's', 'i', 'a', 'y', ' ', 'a', 'a', 'y', ' ', 'e', 's', 't', 't', 'a', 'y']

h = 0

for h in range(len(list)):
    if list[h] in string.whitespace:
        if list[h + 1] in string.punctuation:
            list.pop(h)
            h = h + 1
        else:
            h = h + 1
    else:
        h = h + 1

print(list)

当我 运行 它时,我得到错误:

  File " ... ", line 110, in <module>
    if list[h] in string.whitespace:
IndexError: list index out of range

当我在循环外打印 Hi[h] 时,索引 'h'

没有问题

关于我在哪里犯了错误或我可以改变什么的任何想法?

如果最好能看到完整的文件,请告诉我。

这里有两个列表:hilist,其中 hi 可能是您要尝试转换为 Pig Latin 的字符串。

请注意,您的循环索引正在经历 hi 的长度:for h in range(len(hi)),但在您的代码中,您使用 h 来索引 list,因为示例:if list[h] in string.whitespace。从报错看来,你输入的字符串hilist长,所以当遇到h的值比list长时,它抛出这个错误。

我认为您打算在整个代码中引用 hi(但我可能错了,从您的问题中不清楚),所以只需将 list 的所有实例替换为 hi.

已更新以反映更新后的问题:

在您的代码中 list.pop(h) 从列表中删除元素,从而减小列表的大小。因此,如果在 for h in range(len(list)) 时它最初有 20 个元素长,循环仍然运行到索引 = 19,但是列表不断变短,所以在某些时候,不再有 20 个元素了。

这些情况下的常用策略是向后遍历列表。看看答案here.