与os.walk的嵌套列表理解 [英] nested list comprehension with os.walk
问题描述
试图枚举某个目录中的所有文件(在Linux中为"find.",在Windows中为"dir/s/b").
Trying to enumerate all files in a certain directory (like 'find .' in Linux, or 'dir /s /b' in Windows).
我想出了以下嵌套列表理解:
I came up with the following nested list comprehension:
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)]
不幸的是,对于最后一个表达式,我得到:
Unfortunately, for the last expression, I'm getting:
NameError: name 'files' is not defined
与此问题相关,该问题(尽管有效)我无法理解嵌套列表理解的语法.
Related to this question, which (although working) I can't understand the syntax of the nested list comprehension.
推荐答案
您需要反转嵌套;
allfiles = [join(root,f) for root,dirs,files in walk(root) for f in files]
请参见列表理解文档:
提供列表理解后,它由一个表达式组成,后接至少一个
for
子句和零个或多个for
或if
子句.在这种情况下,新列表的元素是通过将每个for
或if
子句视为一个块,从左向右嵌套,并在每次到达最里面的块.
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.
换句话说,由于您基本上想要道德上等同于:
In other words, since you basically want the moral equivalent of:
allfiles = []
for root, dirs, files in walk(root):
for f in files:
allfiles.append(f)
您的列表理解应遵循相同的顺序.
your list comprehension should follow the same ordering.
这篇关于与os.walk的嵌套列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!