【问题标题】:Python index error in loop when index is in for loop索引在for循环中时循环中的Python索引错误
【发布时间】:2019-04-09 15:26:21
【问题描述】:

我创建的函数中有一个非常奇怪的问题,该函数在类别中搜索单词,如果单词不在其中,则删除该类别。由于一些非常神秘的原因,我总是得到错误:

list index out of range

我了解此错误的含义,但我无法理解原因。 我的代码如下:

def check_cat(input, list_of_words, categories):
"""if a word is not in the possible set of words of a class, cannot be in this class"""
possible_cat = list_of_words
categories_copy = categories
for j in range(len(list_of_words)):
    for i in input:
        if i not in list_of_words[j][:,1]:
            possible_cat.pop(j)
            categories_copy = np.delete(categories_copy,j)
        else:
            pass

categories = array(['culture', 'politics', 'sports'], dtype='|S8')

list_of_words =    
[array([['0.14285714285714285', 'ball'],
            ['0.2857142857142857', 'cart'],
            ['0.14285714285714285', 'drama'],
            ['0.14285714285714285', 'opera'],
            ['0.2857142857142857', 'theater']], dtype='|S32'),
     array([['0.25', 'decision'],
            ['0.5', 'drama'],
            ['0.25', 'strategy']], dtype='|S32'),
     array([['0.2857142857142857', 'ball'],
            ['0.14285714285714285', 'cart'],
            ['0.2857142857142857', 'goal'],
            ['0.14285714285714285', 'player'],
            ['0.14285714285714285', 'strategy']], dtype='|S32')]

我真正不明白的是,当我在函数“外部”/没有函数的情况下执行代码时,它可以工作。但是通过一个函数,我得到了错误:

    File "<ipython-input-110-b499e8f5d937>", line 7, in check_cat
    if i not in list_of_words[j][:,1]:
IndexError: list index out of range

在我看来,索引 j 在 list_of_words 的范围内,因为我在其中循环...任何帮助将不胜感激。

【问题讨论】:

    标签: python loops indexing


    【解决方案1】:

    我认为你的错误的根源在于你的变量赋值。当您在函数内部分配两个变量时,您实际上并没有创建副本,而是创建了指向原始 Python 对象的链接。因此,当您确实 pop 它实际上是在首先读取 len 时减少原始长度的长度,因此循环执行的次数超过了项目的数量。

    这是一个很棒的article,可以更深入地阅读我解释的内容,这是您必须牢记的事情之一,以避免未来的陷阱。

    至于您的问题,我通过复制输入而不是使用.copy() 创建对它的引用进行了小的更改,从而停止了错误。

    possible_cat = list_of_words.copy()
    categories_copy = categories.copy()
    

    希望这可以解决问题,并且是您正在寻找的。

    【讨论】:

      猜你喜欢
      • 2017-08-13
      • 2020-09-09
      • 1970-01-01
      • 2021-07-08
      • 2017-06-24
      • 2013-06-11
      • 2011-12-07
      • 2014-01-14
      相关资源
      最近更新 更多