繁体   English   中英

function中索引错误如何解决

[英]How do i solve the index error in the function

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

比如Delete("hello","helloworld") -> "hello" 然后,我收到以下错误:

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"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM