如何解决函数中的索引错误



我做了一个简单的程序。它删除了2个字符串中的几个不同的子字符串。

Delete("hello","helloworld")->CCD_ 2。然后,我得到了以下错误:

IndexError:从空列表弹出

def Delete(s,t):
list_t=list(t)
list_s=list(s)
while list_t!=list_s:
list_t.pop()
#list_t.pop()
return "".join(list_t)
print(Delete("hello","helloworld"))

您的问题是因为您为每个while迭代调用pop两次。因此,在第三次迭代之后,您将拥有:

list_t -> ['h', 'e', 'l', 'l']
list_s -> ['h', 'e', 'l', 'l', 'o']

这将导致一个无限循环,该循环因您尝试从空列表中pop元素的错误而停止。移除其中一个pop,问题就解决了:

def Delete(s,t):
list_t=list(t)
list_s=list(s)
while list_t!=list_s:
list_t.pop()
#list_t.pop()
return "".join(list_t)
print(Delete("hello","helloworld"))

最新更新