最新消息:

Python对列表list进行for循环遍历时使用remove()删除元素的坑

IT技术 ipcpu 2087浏览 0评论

Python对列表list进行for循环遍历时使用remove()删除元素的坑.md

现象

list_of_char = ['a', 'b', 'b', 'c', 'c', 'd', 'd' ]

for elem in list_of_char:
    if elem == 'b' or elem == 'c':
        list_of_char.remove(elem)
print(list_of_char)

如上,语句,我们期望得到的是['a', 'd', 'd'],但实际得到结果却是['a', 'b', 'c', 'd', 'd']

原因分析

我们来分析下原因,

第一步,a进入循环,不合条件,没有改动,往下走
第二步,b进入循环,符合条件,执行list_of_char.remove('b') 执行以后,列表数据发生变化(remove方法只能删除第一个匹配元素,这个要注意下)
第三步,列表数据发生变化,进入循环的是c,符合条件执行list_of_char.remove('c') 执行以后,列表数据发生变化
第四步,列表数据发生变化,进入循环的是d,不和条件没有改动,往下走
第五步,进入循环的是d,不和条件没有改动,循环结束

如何规避

方法一:复制个新的列表出来,可以使用reversed()或者list()

for elem in reversed(list_of_char):
    if elem == 'b' or elem == 'c':
        list_of_char.remove(elem)

for elem in list(list_of_char):
    if elem == 'b' or elem == 'c':
        list_of_char.remove(elem)

方法二:列表推导式

list_of_char[:] = [x for x in list_of_char if x !='b' and x != 'c']

方法三:使用filter()方法

list_of_char = list(filter(lambda elem: elem != 'b' and elem !='c',list_of_char))

参考资料

https://blog.finxter.com/how-to-remove-items-from-a-list-while-iterating/
https://thispointer.com/python-remove-elements-from-a-list-while-iterating/

转载请注明:IPCPU-网络之路 » Python对列表list进行for循环遍历时使用remove()删除元素的坑

发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (2)

  1. 你这个代码本身没意义 这样不好? list_of_char = ['a', 'b', 'b', 'c', 'c', 'd', 'd' ] while 'c' in list_of_char : list_of_char.remove('c') while 'b' in list_of_char: list_of_char.remove('b') print(list_of_char)
    interim2年前 (2021-12-09)Reply
    • 这样也挺好,主要是一开始不知道这个情况,数据出错了。
      ipcpu2年前 (2022-01-18)Reply