我使用列表理解来仅加载满足特定条件的文件夹中的图像。 在同样的操作中,我还想跟踪那些不符合条件的。这就是我遇到麻烦的地方。
如果
if
和 else
条件位于开头,则每次迭代都会产生一个结果元素。被 else
捕获的项目将被 None
替换,而不是从结果列表中排除。
我不知道如何添加
else
条件,以便可以对 else
捕获的项目执行操作,而不将它们包含在结果列表中。
这是代码的简化和通用版本:
exclude_imgs = [1, 3]
final = [
n
for ix, n in enumerate(sorted(["img1", "img4", "img3", "img5", "img2"]))
if ix + 1 not in exclude_imgs
]
[ins] In [4]: final
Out[4]: ['img2', 'img4', 'img5']
添加
else
条件来存储排除的图像:
exclude_imgs = [1, 3]
excluded = []
final = [
n if ix + 1 not in exclude_imgs else excluded.append(n)
for ix, n in enumerate(sorted(["img1", "img4", "img3", "img5", "img2"]))
]
[ins] In [6]: final
Out[6]: [None, 'img2', None, 'img4', 'img5']
[ins] In [7]: excluded
Out[7]: ['img1', 'img3']
我该如何写才能得到如下结果:
final: ['img2', 'img4', 'img5']
excluded: ['img1', 'img3']
?
考虑根本不使用列表理解,正是因为您想要创建两个列表,而不仅仅是一个。
exclude_imgs = [1, 3]
excluded = []
final = []
for ix, n in enumerate(sorted(["img1", "img4", "img3", "img5", "img2"]), start=1):
(excluded if ix in excluded_imgs else final).append(n)
exclude_imgs = [1, 3]
# convert all element of exclude_imgs into string
exclude_imgs = [str(x) for x in exclude_imgs]
# declare the list of images into a variable so that it is easy to call later. No need to sort
img_lst = ["img1", "img4", "img3", "img5", "img2"]
excluded = []
final = []
# No need to sort
for x in img_lst:
# This condition checks if any of exclude_imgs is present in the image.
if any(y in x for y in exclude_imgs):
excluded.append(x)
else:
final.append(x)
print(excluded) # Output: ['img1', 'img3']
print(final) # Output: ['img4', 'img5', 'img2']