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
相关产品推荐
相关产品推荐

