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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17479465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:19:03  来源:igfitidea点击:

Python: IndexError: list index out of range Error

pythonlistpython-3.x

提问by Kaizer von Maanen

Updated, look bottom!

已更新,请看底部!

I am stuck! I get a IndexError: list index out of range Error.

我被卡住了!我得到一个 IndexError: list index out of range 错误。

def makeInverseIndex(strlist):
    numStrList = list(enumerate(strlist))
    n = 0 
    m = 0 
    dictionary = {}
    while (n < len(strList)-1):
        while (m < len(strlist)-1):
            if numStrList[n][1].split()[m] not in dictionary:
                dictionary[numStrList[n][1].split()[m]] = {numStrList[n][0]}
                m = m+1
            elif {numStrList[n][0]} not in dictionary[numStrList[n][1].split()[m]]:
                dictionary[numStrList[n][1].split()[m]]|{numStrList[n][0]} 
                m = m+1
        n = n+1                
return dictionary

it gives me this error

它给了我这个错误

>>> makeInverseIndex(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "./inverse_index_lab.py", line 23, in makeInverseIndex
    if numStrList[n][1].split()[m] not in dictionary: 
IndexError: list index out of range

I don't get it... what causes this? It happens even when I change the conditions of the while loop. I don't get what is the problem. I am pretty new at this, so explain it like you would if a piece of broccoli asked you this question.

我不明白……这是什么原因?即使我改变了 while 循环的条件,它也会发生。我不明白有什么问题。我对此很陌生,所以请像西兰花问你这个问题一样解释一下。

Edit:

编辑:

Thanks guys, I forgot to mention examples of input, I want to input something like this:

谢谢大家,我忘了提到输入的例子,我想输入这样的东西:

 L=['A B C', 'B C E', 'A E', 'C D A']

and get this as output:

并将其作为输出:

D={'A':{0,2,3}, 'B':{0,1}, 'C':{0,3}, 'D':{3}, 'E':{1,2}}

so to create a dictionary that shows where in the list you might find a 'A' for example. It should work with a huge list. Do anyone have any tips? I want it to iterate and pick out each letter and then assign them a dictionary value.

所以要创建一个字典,显示你在列表中的位置,例如,你可能会找到一个“A”。它应该与一个巨大的列表一起工作。有没有人有任何提示?我希望它迭代并挑选出每个字母,然后为它们分配一个字典值。

Edit number two:

编辑二:

Thanks to great help from you guys my code looks beautiful like this:

感谢你们的大力帮助,我的代码看起来很漂亮:

def makeInverseIndex(strList):
numStrList = list(enumerate(strList))
n = 0
dictionary = {}
while (n < len(strList)):
    for word in numStrList[n][1].split():
        if word not in dictionary:
            dictionary[word] = {numStrList[n][0]}
        elif {numStrList[n][0]} not in dictionary[word]:
            dictionary[word]|={numStrList[n][0]} 
    n = n+1                     

return dictionary

But I still manage to get this error when I try to run the module:

但是当我尝试运行模块时,我仍然设法得到这个错误:

   >>> makeInverseIndex(L)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "./inverse_index_lab.py", line 21, in makeInverseIndex
    for word in numStrList[n][1].split():
NameError: global name 'StrList' is not defined

I do not see where the error can come from.

我不知道错误可能来自哪里。

采纳答案by John Tseng

Good to see some smart veggies programming.

很高兴看到一些智能蔬菜编程。

First, your question. Like @Vasiliy said, you have 3 indices. The nis alright, since you protect it with your whilecondition. The 1is fine since enumeratealways generates 2 things. That just leaves m. This is your problem.

首先,你的问题。就像@Vasiliy 说的,你有 3 个索引。该n是好的,因为你与你的保护它while的条件。这1很好,因为enumerate总是会产生 2 件事。那才离开m。这是你的问题。

Let's say you have Nelements in strlist. For each element ein strlist, you apply split()to it. The number of elements in e.split()is not always equal to N. The while condition for mguards against N, not against len(e.split()), hence the index out of range.

假设您Nstrlist. 对于每一个元素estrlist,你申请split()到它。中的元素数e.split()并不总是等于N。用于m防范的 while 条件N,而不是针对len(e.split()),因此索引超出范围。

To solve this, split the string first, and then loop through it. While you're at it, might as well get rid of maltogether, splitting the string only once, and gain some performance. Plus, you never reset your m, which just grows and grows.

要解决此问题,请先拆分字符串,然后循环遍历它。当你这样做时,不妨m完全摆脱,只拆分一次字符串,并获得一些性能。另外,您永远不会重置您的m,它只会不断增长。

while (n < len(strList)):
    for word in numStrList[n][1].split():
        if word not in dictionary:
            dictionary[word] = {numStrList[n][0]}
        elif {numStrList[n][0]} not in dictionary[word]:
            dictionary[word]|={numStrList[n][0]} 
    n = n+1         

Second, your whileconditions are too restrictive. n < len(strlist)is fine.

其次,你的while条件太严格了。n < len(strlist)很好。

回答by Micaiah Chang

I do not have enough reputation to leave a comment on your post so I'm posting an answer here:

我没有足够的声誉对您的帖子发表评论,所以我在这里发布答案:

I have copy and pasted the latest code at the bottom (edit 2) and it runs as expected, so there are two potential issues I can see:

我在底部复制并粘贴了最新代码(编辑 2),它按预期运行,因此我可以看到两个潜在问题:

1) You might have forgotten to indent your function definition 2) You might have capitalized strList to StrList in your function definition and then declared StrList elsewhere.

1) 您可能忘记缩进函数定义 2) 您可能在函数定义中将 strList 大写为 StrList,然后在其他地方声明 StrList。

Hope this helps.

希望这可以帮助。

回答by MagentoMan

You can always do something like this as well if you want to guard against this error.

如果您想防范此错误,您也可以随时执行此类操作。

try:
    #The code that causes the issue
except IndexError:
    pass