简体   繁体   English

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

[英]Python: IndexError: list index out of range Error

Updated, look bottom! 更新,请看底部!

I am stuck! 我被卡住了! I get a IndexError: list index out of range Error. 我得到IndexError:列表索引超出范围Error。

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. 即使更改了while循环的条件,它也会发生。 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. 我对此很陌生,所以像一块西兰花问您这个问题一样,向您解释。

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. 我希望它进行迭代并挑选出每个字母,然后为其分配一个字典值。

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. 我看不出错误的来源。

Good to see some smart veggies programming. 很高兴看到一些聪明的蔬菜编程。

First, your question. 首先,你的问题。 Like @Vasiliy said, you have 3 indices. 就像@Vasiliy所说的那样,您有3个索引。 The n is alright, since you protect it with your while condition. n很好,因为您可以使用while条件保护它。 The 1 is fine since enumerate always generates 2 things. 1很好,因为enumerate总是生成2件事。 That just leaves m . 剩下m This is your problem. 这是你的问题。

Let's say you have N elements in strlist . 假设您在strlistN元素。 For each element e in strlist , you apply split() to it. 对于strlist每个元素e ,都strlist应用split() The number of elements in e.split() is not always equal to N . e.split()的元素数量并不总是等于N The while condition for m guards against N , not against len(e.split()) , hence the index out of range. 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 m altogether, splitting the string only once, and gain some performance. 当你在它,还不如干掉m干脆,分割字符串只有一次,并获得一些性能。 Plus, you never reset your m , which just grows and grows. 另外,您永远不会重置您的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. 其次,你while条件的限制过于严格。 n < len(strlist) is fine. n < len(strlist)可以。

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. 希望这可以帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM