我要配对的文件夹中有一些图片,因此可以将它们以迭代方式添加到幻灯片中。我想将以mp
结尾的图片与bp
匹配。一个警告是,有多张图片以bp
和bp
结尾,因此添加逻辑检查将是可行的。
让我们说文件夹中有图片
我想将1_birds_bp.png
与其他以1
开始并以mp
结尾的图片配对
以便该对应该看起来像#expected result
('D:\\test\\1_birds_bp.png', 'D:\\test\\1_eagle_mp.png')
('D:\\test\\1_birds_bp.png', 'D:\\test\\1_hawk_mp.png')
('D:\\test\\1_birds_bp.png', 'D:\\test\\1_owl_mp.png')
以及reptile
组
('D:\\test\\2_reptile_bp.png', 'D:\\test\\2_crocodile_mp.png')
('D:\\test\\2_reptile_bp.png', 'D:\\test\\2_snake_mp.png')
因此,请遵循此post 我尝试过
def image_pairs(folder):
bp, mp = [], []
for image_path in glob.glob(folder + '/*.png'):
if "bp" in image_path:
bp.append(image_path)
elif "mp" in image_path:
mp.append(image_path)
for pair in zip(bp, mp):
print(pair)
#yield pair
但我可以配对唯一
('D:\\test\\1_birds_bp.png', 'D:\\test\\1_eagle_mp.png')
('D:\\test\\2_reptile_bp.png', 'D:\\test\\1_hawk_mp.png')
如何实现呢?
答案 0 :(得分:1)
您可以检查所有组合并选择匹配的组合:
from itertools import combinations
from pathlib import Path
files = Path(folder).glob('*.png')
list_of_pairs = [(a, b) for a, b in combinations(files, 2)
if (a.name.startswith(b.name[0]) and (('mp' in a.name and 'bp' in b.name) or ('bp' in a.name and 'mp' in b.name))]
更好的是,在filter
上使用itertools.combinations
进行自定义成对检查。
答案 1 :(得分:1)
我喜欢@xletmjm的方法,尽管import sys
from clang import cindex
tu = cindex.Index.create().parse('./t.cc', args=[], unsaved_files=[
('./t.h', ''),
('./t.cc', '#include "t.h"'),
])
for diag in tu.diagnostics:
sys.stderr.write(diag.format() + "\n")
仅在Python> = 3.4中可用。
这是一种替代方法,可与您到目前为止使用的方法一起使用。
pathlib