Python 列表切片错误



我正在使用以下代码:https://pastebin.com/mQkpxdeV

    wordlist[overticker] = thesentence[0:spaces]

在此函数中:

def mediumparser(inpdat3):
    spaceswitch = 0
    overticker = 0
    thesentence = "this sentence is to count the spaces"
    wordlist = []
    while spaceswitch == 0:
        spaces = thesentence.find(' ')
        wordlist[overticker] = thesentence[0:spaces] # this is where we save the words at
        thesentence = thesentence[spaces:len(thesentence)] # this is where we change the sentence for the
                                                            # next run-through
        print('here2')
        print(wordlist)

我不知道为什么它一直说列表索引超出范围。

该程序似乎可以工作,但它给出了一个错误,我做错了什么?我翻阅了马克·卢茨(Mark Lutz(的这本书,寻找答案,但我找不到答案。

"列表索引超出范围"问题从来都不是列表拼接,如以下简单测试所示:

>>> l = []
>>> l[0:1200]
[]
>>> l[-400:1200]
[]

所以问题出在你的左手分配wordlist[overticker]它使用列表访问,而不是切片,并且受"列表索引超出范围"的影响。

只需这 4 行代码就足以找到问题所在

wordlist = []
while spaceswitch == 0:
    spaces = thesentence.find(' ')
    wordlist[overticker] = ...

wordlist只是空的。您必须扩展/附加列表(如果要根据键动态创建项目,请使用字典(

而不是wordlist[overticker] wordlist是空列表,而是需要使用 append,因为索引空列表没有意义。

wordlist.append(thesentence[0:spaces])

或者,您可以使用 20 个空字符串预先启动列表。

wordlist = [""]*20  
wordlist[overticker] = thesentence[0:spaces]

附言

wordlist[overticker]称为索引,wordlist[1:10]称为切片。

相关内容

最新更新