Python中的while循环错误

2024-04-27 04:53:50 发布

您现在位置: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错误。我明白错误的含义,但不确定我做错了什么。奇怪的是,只有当我运行上面的代码时才会发生这种情况。运行此程序时不会出现任何错误:

^{pr2}$

我对Python相当陌生(将持续三天),所以我确信这是一个被忽略的愚蠢语法错误。。。在


Tags: 代码inlenis错误testingsomethinglist
3条回答
while i < len(listofshit):
    l = i + 1
    x = listofshit[i]
    y = listofshit[l]

i对应于最后一个元素时

^{pr2}$

您正试图访问最后一个元素旁边的元素。这就是它抛出错误的原因。在

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

列表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 

相关问题 更多 >