python出现indexerror,Python:IndexError:列表索引超出范围错误

本文探讨了Python中处理字符串列表时出现的IndexError:list index out of range错误,并提供了一个修正后的函数来创建逆向索引。该函数能够遍历输入的字符串列表并为每个单词建立一个索引,用于跟踪这些单词在列表中的位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 "", line 1, in

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 "", line 1, in

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值