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

Python遍历列表删除元素时字符串长度判断结果异常如何解决?

问题原因

直接在遍历原列表的过程中删除元素,会导致列表长度动态收缩、后续元素索引前移,而for循环的遍历指针仍按原有顺序向后移动,最终会跳过部分元素的检查,出现漏删的情况。

解决方案

以下几种方式都可以实现预期效果:

  • 方案1:使用列表推导式生成新列表(最推荐,写法简洁高效)
stuff = ["apple", "jam", "banana", "bread", "corn", "orange", "tea", "peanut"]
stuff = [word for word in stuff if len(word) == 3]
print(stuff)
  • 方案2:遍历原列表的浅拷贝,删除原列表中不符合要求的元素
stuff = ["apple", "jam", "banana", "bread", "corn", "orange", "tea", "peanut"]
for word in list(stuff): # list(stuff)生成原列表的浅拷贝
    if len(word) != 3:
        stuff.remove(word)
print(stuff)
  • 方案3:倒序遍历原列表索引,删除不符合要求的元素
stuff = ["apple", "jam", "banana", "bread", "corn", "orange", "tea", "peanut"]
for i in range(len(stuff)-1, -1, -1):
    if len(stuff[i]) != 3:
        del stuff[i]
print(stuff)

三种方案运行后均会输出预期结果:

['jam', 'tea']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:06:05