python - 从可能的目录列表中获取文件的平面列表的单行程序?

标签 python list python-2.7 directory

假设我们有一个目录列表,其中一些可能不存在:

dirs = ['dir1','dir2','dir3']

为了论证,只有两个存在,它们的内容是:

dir1
  --file1a
  --file1b
dir2
  --file2a
  --file2b

What is the best one-liner to get a flat list of all the files? The closest I got was:

import os
files = [ os.listdir(x) for x in ['dir1','dir','dir3'] if os.path.isdir(x) ]

但这给了我一个嵌套列表:

[['file1a','file1b'],['file2a','file2b']]

如果我希望它是 ['file1a', 'file1b', 'file2a', 'file2b'],我必须使用什么单行代码?

最佳答案

您可以将项目链接到一个列表中:

from itertools import chain as ch


files = list(ch.from_iterable(os.listdir(x) for x in ['dir1', 'dir', 'dir3'] if os.path.isdir(x)))

我能做到的最短时间:

from itertools import chain as ch, ifilter as ifil, imap 
from os import path, listdir

files = list(ch.from_iterable(imap(listdir, ifil(path.isdir, ('dir1', 'dir', 'dir3')))))

如果您只想使用名称,那么只需遍历链对象即可。

关于python - 从可能的目录列表中获取文件的平面列表的单行程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28726903/

相关文章:

python - 为 Python 解释器建立的每个连接绑定(bind)传出 IP 地址

python - pandas:计算出每天每只股票的平均值和总值(value)

c# - 使用 Linq 读取第 n 层列表并将所需数据保存到另一个列表

wpf - 在文件夹中搜索和列出 WPF 资源字典

python - 根据键 ckeys 之一的值对字典值进行排序

python - 类型错误 : unsupported operand type(s) for ** or pow(): 'str' and 'int'

Python tar.add 文件但省略父目录

python - Apache Beam + 大查询表读取

AWS Beanstalk 上的 Python。如何快照自定义日志?

python - 为什么这个 Python 脚本会崩溃?