简体   繁体   中英

Python: IndexError: list index out of range Error

Updated, look bottom!

I am stuck! I get a IndexError: list index out of range 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. 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. 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.

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.

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.

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.

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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