1

以下のような構成がありますが、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
4

2 に答える 2

4

sの順序は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
   ]

基本的に、ネストされたfors をリスト内包表記に変換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)
]
于 2013-03-11T18:14:47.490 に答える
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]

しかし、あなたの最初のバージョンは本当に読みやすいです。

于 2013-03-11T18:22:11.943 に答える