博客
关于我
python 用for循环删除list列表中的元素,删除不干净的问题
阅读量:301 次
发布时间:2019-03-03

本文共 840 字,大约阅读时间需要 2 分钟。

在处理列表时,使用remove方法删除元素可能会导致循环出错,因为删除会改变列表结构,影响索引。使用切片list1[:]确保循环不受影响。


今天遇到了一个有趣的Python问题,需要从一个列表中删除特定类型的元素。具体来说,列表里的元素是文件名,分为.txt和.jpg两种类型,目标是删除所有.txt文件,只保留.jpg文件。

为了实现这个目标,我写了如下的代码:

list1 = ['a.txt','b.txt','c.txt','a.jpg','b.jpg','c.jpg']for im in list1:    if im.split('.')[-1] != 'jpg':        list1.remove(im)print(list1)

运行后,输出结果是['b.txt', 'a.jpg', 'b.jpg', 'c.jpg']。这显然不对,因为预期只剩下.jpg文件,而b.txt却没有被删除。

经过进一步研究,我发现问题出在循环过程中使用remove方法删除元素上。当删除一个元素时,后面的元素索引会自动调整,这会导致循环中某些元素被跳过或重复处理,从而出现意外的结果。

为了修正这个问题,我在循环中使用了list1[:], 这样在循环处理时,列表的元素不会随着删除而改变。修改后的代码如下:

list1 = ['a.txt','b.txt','c.txt','a.jpg','b.jpg','c.jpg']for im in list1[:]:    if im.split('.')[-1] != 'jpg':        list1.remove(im)print(list1)

运行后,结果变为['a.jpg', 'b.jpg', 'c.jpg'],这正是预期的结果。

总结一下,使用remove方法删除列表中的元素时,循环过程中不要修改列表的长度和结构,否则可能导致循环出错。使用切片list1[:]可以创建一个静态的列表,这样循环就不会受影响了。

转载地址:http://zvgl.baihongyu.com/

你可能感兴趣的文章
Notepad ++ 安装与配置教程(非常详细)从零基础入门到精通,看完这一篇就够了
查看>>
Notepad++在线和离线安装JSON格式化插件
查看>>
notepad++最详情汇总
查看>>
notepad++正则表达式替换字符串详解
查看>>
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notes on Paul Irish's "Things I learned from the jQuery source" casts
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
NotImplementedError: Could not run torchvision::nms
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! fatal: unable to connect to github.com:
查看>>
npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>