2013-03-11 53 views
1

我有一個像下面這樣的構造,我如何使用1(或更多)列表解析來獲得相同的輸出?如何在列表理解中表示嵌套的fors?

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 
+0

不應該你的if語句被選中嗎?另外你的語法錯誤是什麼? – mydogisbox 2013-03-11 18:13:54

+0

你的評論說你得到'syntax'錯誤,而回溯顯示'NameError'。 – 2013-03-11 18:22:52

+0

@AshwiniChaudhary我的壞...看着一個不同的腳本...(:P給我) – pradyunsg 2013-03-11 18:25:30

回答

4

for s量級不會改變。你的情況的條件變得尷尬:

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

有沒有任何方法不會調用'parse_name()'兩次,這是一個非常緩慢的功能.. – pradyunsg 2013-03-11 18:22:07

+1

@Schoolboy - 是。 '...如果x和(ref-x).days> = 0] x in(parse_name(item),)os.path.isdir(os.path.join(path,item))' – 2013-03-11 18:31:01

+0

@Robᵩ考慮發佈它作爲答案我會投票它(雖然我會接受這個答案) – pradyunsg 2013-03-11 18:33:24

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] 

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