我是一名编程专业的学生,最近刚开始使用Python。我从学习Rackett开始,它有一个非常不同的方法。在尝试将递归与for语句结合使用时,我遇到了“IndexError:list index out out-range”。这是我的代码:
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
我认为我的函数在递归时不会使用reduced list,至少在
range(len(l) - 1)
非常感谢您的帮助,谢谢。在
我不能确定没有更多的信息,但问题似乎是你在迭代列表时突然从列表中弹出。同样,如果没有更多的信息(比如你想做什么),我不知道该怎么解决。在
列表“l”变空,而您仍在尝试运行循环。唐'列表为空时不运行此循环。 此外,该循环应为范围内的i(len(l))。在
相关问题 更多 >
编程相关推荐