如何在列表推导中表示嵌套的fors?

时间:2013-03-11 18:11:29

标签: python list list-comprehension

我有一个类似下面的结构,如何使用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

2 个答案:

答案 0 :(得分:4)

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转换为列表理解,您只需移动append前面的任何内容:

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)
]

答案 1 :(得分:2)

这应该可以胜任,

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

但您的初始版本更具可读性。

相关问题