Python - FOR 循环按文件扩展名删除列表项 [英] Python - FOR loop to remove list items by file extension
问题描述
我一定遗漏了一些基本的东西,因为我已经有一段时间没有使用 Python 了.我有一个简单的函数,我想从目录中返回 .jpg 的列表,但它也返回其他文件.
导入操作系统def myFunction(目录):图片 = os.listdir(目录)对于枚举(图片)中的 i,v:如果 v[-3:] != 'jpg':图片.pop(i)返回排序(图片)
同一目录下有 .gif 和 .htm 文件..gif 文件不会与列表一起返回,但 .htm 文件会返回.如果我在解释器中运行这个循环,我可以看到 .gif 文件被弹出,然后如果我第二次运行循环,则 .htm 文件被弹出.
我错过了什么?感谢您的帮助.
在迭代列表时不应更改列表.这将破坏索引.
使用列表理解:
<预><代码>>>>图片 = ['abc.jpg', 'abc.gif', 'abc.png', 'cde.jpg']>>>[pic for pic in picture if pic.endswith('jpg')]['abc.jpg', 'cde.jpg']或 filter()
和 lambda()
:
I must be missing something fundamental as it's been a while since I've used python. I have a simple function that I'd like to return a list of .jpg's from a directory, but it is returning other files as well.
import os
def myFunction(directory):
pictures = os.listdir(directory)
for i,v in enumerate(pictures):
if v[-3:] != 'jpg':
pictures.pop(i)
return sorted(pictures)
There are .gif and .htm files in the same directory. The .gif file isn't returned with the list, but the .htm file is. If I run this loop in the interpreter, I can see the .gif file gets popped, and then if I run the loop a second time, the .htm file gets popped.
What am I missing? Thanks for the help.
You should not change the list while iterating over it. That will screw the indexing.
Use list comprehension:
>>> pictures = ['abc.jpg', 'abc.gif', 'abc.png', 'cde.jpg']
>>> [pic for pic in pictures if pic.endswith('jpg')]
['abc.jpg', 'cde.jpg']
Or filter()
with lambda()
:
>>> filter(lambda pic: pic.endswith('jpg'), pictures)
['abc.jpg', 'cde.jpg']
这篇关于Python - FOR 循环按文件扩展名删除列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!