2016-07-11 9 views
0

私が探しているのは、リストを検索し、いくつかの他のリストに基づいて項目をフィルタリングする正しい方法です。リストの作成に役立つ必要があります。いくつかの除外項目の使い方

imageList = ['green_D.jpg', 'red_D.gif', 'orange_R.jpg', 'black_S.gif', 'folder_A', 'folder_B'] 
included_extensions = ['jpg', 'bmp', 'png', 'gif'] 
excluded_textures = ['_R.', '_A.', '_S.'] 

私はその後、私のイメージリストを反復し、incuded_extensionsを使用して画像のみをフィルタリングして、excluded_texturesに指定されたすべてのテクスチャ略語をフィルタリングします。

私は、コードに失敗しました:結果はその後、この場合だけでは

newImageList = ['green_D.jpg', 'red_D.gif'] 
+4

'[私はimageList内にあります(もしextが含まれていれば)、そうでなければ(extはiがextを除外しています)]'? – Bakuriu

+5

あなたは標準的なネストされたループとしてこれを書いて、*それからリストの理解を構成しようとするのが良いでしょう。 – jonrsharpe

+0

ちなみに、何かがリスト内包として書かれていても、それはリスト内包として書くべきではありません。可読性は数えます! – DeepSpace

答えて

2

が含まれている必要があり

newImageList = [ (img for img in imageList) if (tex for tex in excluded_textures) not in img and any(img.endswith(ext) in img for ext in included_extensions)] 

を、私はループを使用したい - 単一のリスト-理解にそれをすべてれる詰め込みます...あなたが欲しいものを本当にはないかを理解するために、コードを困難にするつもり:

imageList = ['green_D.jpg', 'red_D.gif', 'orange_R.jpg', 'black_S.gif', 'folder_A', 'folder_B'] 
included_extensions = ('jpg', 'bmp', 'png', 'gif') # Note, tuple. 
excluded_textures = ('_R.', '_A.', '_S.') 

newImageList = [] 
for img in imageList: 
    # If the extension isn't included, just continue the loop. 
    if not img.endswith(included_extensions): # str.endswith accepts tuple, but not list (see change above). 
     continue 

    # Split off the extension so we can test the excluded_textures 
    base, _ = os.path.splitext(img) 
    # If the image's base ends with an excluded texture, just continue the loop. 
    if (base + '.').endswith(excluded_textures): 
     continue 

    # The image has passed all of the validation we threw at it. Add 
    # it to the newImageList. 
    newImageList.append(img) 

私はちょうどそれテストしてみましたdこのコードは正しい出力を与えます。

+0

__included_extensions__を 'list'から' tuple'に変更した理由を説明できますか?これはスピードに関連していますか? –

+0

クリーンなコードのためのUpvote ..最後のif文がどのように機能するか説明できますか? –

+1

@ Ev.Kounis - 'str.startswith'と' str.endswith'は 'tuple'を受け入れますが' list'は受け付けません。 – mgilson

1
imageList = ['green_D.jpg', 'red_D.gif', 'orange_R.jpg', 'black_S.gif', 'folder_A', 'folder_B'] 
included_extensions = ['jpg', 'bmp', 'png', 'gif'] 
excluded_textures = ['_R.', '_A.', '_S.'] 

print filter(lambda x:x[-3:] in included_extensions and x[-6:-3] not in excluded_textures,imageList) 
0
In [16]: new_list = [img for img in imageList if any(img.endswith(good_ext) for 
    ...: good_ext in included_extensions) and not any(bad_tex in img for bad_tex 
    ...: in excluded_textures)] 

In [17]: new_list 
Out[17]: ['green_D.jpg', 'red_D.gif'] 

あなたが本当にリスト内包でこれを行うにしたい場合は、ここで方法です。

+0

FWIWでは、 'included_extensionsのgood_extのためのimg.endswith(good_ext)'は 'img.endswith(tuple(included_extensions))'と書くことができ、 'included_extensions'が' tuple'であれば、書く。 – mgilson

+0

ありがとうございました!再度スタックオーバーフローが救助に来ます! – NaughtyDag

関連する問題