" IndexError:列表索引超出范围"在列表上使用递归时

时间:2017-12-04 17:55:12

标签: python for-loop recursion indexing range

我是一名编程学生,我刚刚开始使用Python。我开始学习Rackett,它有一个非常不同的方法。在尝试将递归与for语句结合使用时,我遇到了" IndexError:list index超出范围"。这是我的代码:

def search_matching_pokemon(p, l):
    lp = []
    for i in range(len(l) - 1):
        if p[-1] == l[i][0]:
            print ('Found one')
            poke = l.pop(i)
            lp = lp + [poke]
            print (f'List is now {lp}')
            search_matching_pokemon(poke, l)    #problem with the range
        else:
            print ('Trying a different pokémon')
    return lp

我认为我的函数在递归时不会采用缩减列表,至少在此期间不会 range(len(l) - 1) 非常感谢帮助,谢谢你。

2 个答案:

答案 0 :(得分:0)

我无法确定没有更多信息,但看起来问题是你在迭代它时从列表中弹出。再说一次,如果没有更多信息(比如你要做的事情),我无法确定如何解决这个问题。

答案 1 :(得分:0)

列表“l”变为空,您仍然在尝试运行循环。当列表为空时,不要运行此循环。 循环也应该是i在范围内(len(l))。