nested list comprehension with os.walk
试图枚举某个目录中的所有文件(如Linux中的"find."或Windows中的"dir/s/b")。
我提出了以下嵌套列表理解:
1 2 3 4 | from os import walk from os.path import join root = r'c:\windows' #choose any folder here allfiles = [join(root,f) for f in files for root,dirs,files in walk(root)] |
不幸的是,对于最后一个表达,我得到:
与这个问题相关,这个问题(尽管有效)我不能理解嵌套列表理解的语法。
你需要扭转嵌套;
1 | allfiles = [join(root,f) for root,dirs,files in walk(root) for f in files] |
号
参见列表理解文档:
When a list comprehension is supplied, it consists of a single expression followed by at least one
for clause and zero or morefor orif clauses. In this case, the elements of the new list are those that would be produced by considering each of thefor orif clauses a block, nesting from left to right, and evaluating the expression to produce a list element each time the innermost block is reached.
号
换言之,因为你基本上想要道德上等同于:
1 2 3 4 | allfiles = [] for root, dirs, files in walk(root): for f in files: allfiles.append(f) |
你的清单理解应该遵循同样的顺序。
它是:
1 | allfiles = [join(root, f) for _, dirs, files in walk(root) for f in files] |