Skip to main content
 首页 » 编程设计

python之我如何在列表理解中表示嵌套 for

2025年05月04日19unruledboy

我有一个类似于下面的构造,我如何使用 1 个(或多个)列表推导来获得相同的输出?

f2remove = [] 
for path in (a,b): 
    for item in os.listdir(path): 
        if os.path.isdir(os.path.join(path,item)): 
            x = parse_name(item) 
            if x and (ref - x).days >= 0: 
                f2remove.append(os.path.join(path,item)) 

我试过很多东西,比如

files = [parse_name(item)\ 
         for item in os.listdir(path) \ 
         for path in (a,b)\ 
         if os.path.isdir(os.path.join(path,item))] # get name error 
f2remove = [] # problem, don't have path... 

错误:

Traceback (most recent call last): 
  File "C:\Users\karuna\Desktop\test.py", line 33, in <module> 
    for item in os.listdir(path) \ 
NameError: name 'path' is not defined 

请您参考如下方法:

for 的顺序不变。你的情况变得尴尬:

f2remove = [ 
    os.path.join(path, item) 
    for path in (a,b) 
        for item in os.listdir(path) 
            if os.path.isdir(os.path.join(path, item)) 
               for x in (parse_name(item),) 
                  if x and (ref - x).days >= 0 
   ] 

基本上,要将嵌套的 for 转换为列表推导式,您只需将要附加的内容移到前面:

result = [] 
for a in A: 
    for b in B: 
      if test(a, b): 
         result.append((a, b)) 

成为

result = [ 
    (a, b) 
    for a in A 
    for b in B 
    if test(a, b) 
]