博客
关于我
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/

你可能感兴趣的文章
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
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install CERT_HAS_EXPIRED解决方法
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install 卡着不动的解决方法
查看>>
npm install 报错 EEXIST File exists 的解决方法
查看>>
npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
查看>>
npm install 报错 Failed to connect to github.com port 443 的解决方法
查看>>
npm install 报错 fatal: unable to connect to github.com 的解决方法
查看>>
npm install 报错 no such file or directory 的解决方法
查看>>
npm install 权限问题
查看>>
npm install报错,证书验证失败unable to get local issuer certificate
查看>>
npm install无法生成node_modules的解决方法
查看>>