You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决字符串处理函数中的IndexError: pop from empty list错误

解决IndexError: pop from empty list的问题

咱们来一步步拆解这个问题哈~首先你的代码出现IndexError: pop from empty list,主要有几个明显的问题,我给你捋清楚:

问题根源

  • return语句缩进错误:你把return "".join(list_t)写在while循环内部了,导致第一次执行list_t.pop()之后直接返回结果,根本没机会完成多次pop得到目标字符串。
  • 循环条件未做长度限制:只判断list_t != list_s,如果传入的s比t长(比如调用Delete("helloworld", "hello")),list_t会被不断pop直到空列表,此时再执行pop()就会触发索引错误。
  • 逻辑假设不严谨:默认t的前缀和s完全匹配,但如果两者开头就不一致,循环会一直执行到list_t为空,同样会报错。

修正方案

方案1:针对你的示例需求(t以s开头时,删除t的后缀差异)

这个方案严格匹配你给出的示例场景,只有当t的前缀和s完全一致且t更长时,才删除t的后缀部分:

def Delete(s,t):
    list_t = list(t)
    list_s = list(s)
    # 限制循环条件:只有t比s长,且t的前缀等于s时才继续pop
    while len(list_t) > len(list_s) and list_t[:len(list_s)] == list_s:
        list_t.pop()
    return "".join(list_t)

print(Delete("hello","helloworld"))  # 输出 "hello"
print(Delete("helloworld","hello"))  # 输出 "hello"(t比s短,直接返回原t)
print(Delete("hello","h3lloworld"))  # 输出 "h3lloworld"(前缀不匹配,直接返回原t)

方案2:通用场景(获取两个字符串的最长公共前缀)

如果你的需求是不管输入顺序,都返回两个字符串的最长公共前缀,可以用更高效的逻辑:

def Delete(s,t):
    min_length = min(len(s), len(t))
    common_length = 0
    # 逐个字符对比,找到最长公共前缀的长度
    while common_length < min_length and s[common_length] == t[common_length]:
        common_length += 1
    # 返回t的公共前缀部分
    return t[:common_length]

print(Delete("hello","helloworld"))  # 输出 "hello"
print(Delete("helloworld","hello"))  # 输出 "hello"
print(Delete("hello","h3llo"))       # 输出 "h"

验证原错误场景

原代码中如果调用Delete("helloworld","hello"),list_t会被不断pop直到空,触发IndexError。用上面的修正方案就能避免这个问题,同时保证逻辑符合预期。

内容的提问来源于stack exchange,提问作者user12645525

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 00:47:53