Python: IndexError:超出范围的索引

时间:2022-04-19 16:40:39

Updated, look bottom!

更新,看下!

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

我卡住了!我得到一个IndexError:超出范围的索引。

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:

编辑2号:

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.

我不知道错误的来源。

3 个解决方案

#1


4  

Good to see some smart veggies programming.

很高兴看到一些聪明的蔬菜编程。

First, your question. Like @Vasiliy said, you have 3 indices. The n is alright, since you protect it with your while condition. The 1 is fine since enumerate always generates 2 things. That just leaves m. This is your problem.

首先,你的问题。就像@Vasiliy说的,你有三个指标。n是可以的,因为你用while条件来保护它。1可以,因为枚举总是生成2个东西。只剩下m,这是你的问题。

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

假设在strlist中有N个元素。对于strlist中的每个元素e,都对其应用split()。e.split()中的元素数并不总是等于N。m对N的while条件,而不是对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 m altogether, 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 while conditions are too restrictive. n < len(strlist) is fine.

第二,你的while条件太苛刻。n < len(strlist)可以。

#2


1  

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.

希望这个有帮助。

#3


0  

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

#1


4  

Good to see some smart veggies programming.

很高兴看到一些聪明的蔬菜编程。

First, your question. Like @Vasiliy said, you have 3 indices. The n is alright, since you protect it with your while condition. The 1 is fine since enumerate always generates 2 things. That just leaves m. This is your problem.

首先,你的问题。就像@Vasiliy说的,你有三个指标。n是可以的,因为你用while条件来保护它。1可以,因为枚举总是生成2个东西。只剩下m,这是你的问题。

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

假设在strlist中有N个元素。对于strlist中的每个元素e,都对其应用split()。e.split()中的元素数并不总是等于N。m对N的while条件,而不是对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 m altogether, 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 while conditions are too restrictive. n < len(strlist) is fine.

第二,你的while条件太苛刻。n < len(strlist)可以。

#2


1  

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.

希望这个有帮助。

#3


0  

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