Python函数内循环触发IndexError:列表索引越界问题求助
解决列表遍历修改导致的IndexError问题
嘿,我一眼就看穿你遇到的问题啦!这个IndexError: list index out of range完全是因为你在遍历列表的同时直接修改了它的长度,导致后续循环的索引超出了列表实际的范围。咱们一步步拆解问题,再给出修复方案:
问题根源分析
遍历与修改列表的冲突
你用for j in range(len(list_of_words))循环,但possible_cat = list_of_words意味着possible_cat是原列表的别名——也就是说,你调用possible_cat.pop(j)时,直接修改了list_of_words的长度!
举个例子:初始list_of_words长度是3,第一次pop后长度变成2,但循环还是会按原长度3继续执行,当j=2时,列表已经只有2个元素(索引0和1),自然就触发索引越界错误了。numpy数组的引用陷阱
categories_copy = categories并没有创建数组的副本,只是让变量指向原数组的引用。后续用np.delete虽然会返回新数组,但同步删除的逻辑和列表的问题一样,会因为索引变化导致错误。额外小问题
参数名input是Python内置函数名,用它做参数会覆盖内置函数,建议改成input_words这类名称。
修复后的代码
我们换一种思路:先收集所有需要保留的类别索引,再批量生成结果,避免遍历中修改原列表。
import numpy as np def check_cat(input_words, list_of_words, categories): """if a word is not in the possible set of words of a class, cannot be in this class""" # 收集所有符合条件的类别索引 keep_indices = [] for j in range(len(list_of_words)): # 检查当前类别是否包含所有输入词汇 all_words_present = True for word in input_words: if word not in list_of_words[j][:, 1]: all_words_present = False break if all_words_present: keep_indices.append(j) # 根据保留索引生成新的结果 possible_cat = [list_of_words[j] for j in keep_indices] categories_copy = categories[keep_indices] return possible_cat, categories_copy
代码逻辑说明
- 先遍历每个类别,检查输入的所有词汇是否都存在于该类别的词集中,把符合条件的类别索引存入
keep_indices - 最后用列表推导式和numpy数组索引,直接生成过滤后的
possible_cat和categories_copy - 这种方式完全避免了遍历中修改原列表的问题,逻辑更清晰,也不会触发索引错误
内容的提问来源于stack exchange,提问作者Joachim
相关产品推荐
相关产品推荐

