而Python中的循环错误

时间:2013-11-23 05:07:41

标签: python

我很感激帮助调试此代码:

testing = """There is something unique about this line
in that it can span across several lines, which is unique and
useful in python."""

listofthings = []

i = 0
while i < len(testing):
    if testing[i] == " ":
        listofthings.append(i + 1)

    i = i + 1

listofthings.insert(0, 0)
listofthings.append(len(testing))

print listofthings

word_list = []

i = 0

while i < len(listofthings):
    l = i + 1
    x = listofthings[i]
    y = listofthings[l]

    word = testing[x:y]
    word_list.append(word)

    i = l

print word_list 

我不确定为什么会收到index out of range错误。我明白这个错误意味着什么,但我不确定我做错了什么。奇怪的是,这只发生在我运行上面的代码时。当我运行它时,它不会给我任何错误:

word = testing[x:y]
print word

我是Python的新手(三天后),所以我确信这是一个愚蠢的语法错误......

4 个答案:

答案 0 :(得分:3)

l = i + 1
x = listofshit[i]
y = listofshit[l]

word = testing[x:y]
word_list.append(word)

i=length-1,然后y=length,这是一个错误.Python数组索引从0开始,因此最大地址为length-1

答案 1 :(得分:1)

while i < len(listofshit):
    l = i + 1
    x = listofshit[i]
    y = listofshit[l]

i对应最后一个元素时,

    y = listofshit[l]

您正尝试访问最后一个元素旁边的元素。这就是为什么它会抛出错误。

答案 2 :(得分:1)

列表listofshit的长度为21,索引范围为0到20.当涉及到最终循环时,i为20,l为21,所以有一个超出范围的错误。我认为以下代码是您想要的:

testing = """There is something unique about this line
in that it can span across several lines, which is unique and
useful in python."""

listofshit = []

i = 0
while i < len(testing):
    if testing[i] == " ":
        listofshit.append(i)

    i = i + 1

listofshit.insert(0, 0)
listofshit.append(len(testing))


word_list = []
i = 0

while i < len(listofshit) - 1:
    l = i + 1
    x = listofshit[i]
    y = listofshit[l]
    word = testing[x:y]
    word_list.append(word)

    i = l

print word_list 

答案 3 :(得分:0)

在第二个while循环的最后一次迭代中,l设置为len(listofshit)。这已经过了listofshit;最后一个有效索引是len(listofshit) - 1