gpt4 book ai didi

python - 使用 if 条件列表理解以获取特定类型的文件列表

转载 作者:行者123 更新时间:2023-11-28 22:45:22 25 4
gpt4 key购买 nike

大致遵循 this solution 中描述的将列表理解与 if-else 放在一起的逻辑,我正在尝试获取父目录下具有特定扩展名的文件列表。

这是代码的完整形式:

mxd_list = []
for top_dir, dir_list, obj_list in os.walk(top_path):
for obj in obj_list:
if obj.endswith('.mxd'):
mxd_list.append(os.path.join(top_dir, obj))

这是我目前尝试使用列表理解来巩固这一点。虽然它运行了,但列表是空的。

for top_dir, dir_list, obj_list in os.walk(top_path):
mxd_list = [os.path.join(top_dir, obj) for obj in obj_list if obj.endswith('.mxd')]

最佳答案

你离得很近。您需要附加到循环外的列表

mxd_list = []
for top_dir, dir_list, obj_list in os.walk(top_path):
mxd_list.extend([os.path.join(top_dir, obj) for obj in obj_list if obj.endswith('.mxd')])

错误在于 - 在外部 for 循环的每次迭代中,列表 comp 只会生成一个特定于该迭代的列表,因此您需要扩展每次迭代后生成的每个列表到外部变量 mxd_list

注意 - [ 是多余的,因为删除它们会使内容成为生成器表达式。也就是说,语句可以写成 mxd_list.extend(os.path.join(top_dir, obj) for obj in obj_list if obj.endswith('.mxd'))

另一种方法 - 使用 glob.iglob

As Padraic mentions

mxd_list = []
for top_dir, dir_list, obj_list in os.walk(top_path):
mxd_list.extend(iglob(top_dir+"/*.mxd"))

是一种更好的方法。但是不要忘记导入模块,即from glob import iglob

关于python - 使用 if 条件列表理解以获取特定类型的文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28682226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com