【问题标题】:How do i solve the index error in the function如何解决函数中的索引错误
【发布时间】:2020-12-18 14:20:46
【问题描述】:

我做了一个简单的程序。它删除了 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"))

【问题讨论】:

    标签: python algorithm index-error


    【解决方案1】:

    您的问题是因为每次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"))
    

    【讨论】:

      猜你喜欢
      • 2017-04-29
      • 1970-01-01
      • 2013-02-14
      • 2014-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      相关资源
      最近更新 更多