在list comprhensions上需要帮助。如何使用多个排除

时间:2016-07-11 15:09:53

标签: python list-comprehension

所以我正在寻找的是搜索列表并根据其他几个列表过滤项目的正确方法。

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.']

我想迭代我的 imageList 并使用 incuded_extensions 过滤掉图像,然后过滤掉 excluded_textures 中指定的所有纹理缩写。< / p>

我失败的代码:

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

结果应该只包含

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

3 个答案:

答案 0 :(得分:2)

在这种情况下,我会使用一个循环 - 将其全部填充到单个列表中 - 理解将使代码更难理解哪个不是你想要的......:

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)

我刚测试了它,这段代码给出了正确的输出。

答案 1 :(得分: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)

答案 2 :(得分: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']

如果你真的想用列表理解这样做,那么如何做。 (不太可读)