如何将CSV中的匹配图像对合并为含3个及以上元素的去重分组
代码问题排查
你的代码存在3个核心错误,导致文件缺失:
- 逻辑判断变量用错:你提前将
_first定义为布尔值(表示_match[0]是否存在),后续判断if _first in _node本质是在节点列表中查找布尔值True/False,永远匹配失败,自然不会把新文件加入分组。 - 未覆盖两个文件都已存在的分支:当配对的两个文件都已经被录入
_exists时,你的代码没有对应处理逻辑,这条配对会被直接跳过,如果两个文件此前被分到不同分组,还会导致同一组重复文件被拆成多个分组。 - 效率缺陷:用列表存储
_exists,in查询时间复杂度为O(n),文件量大时运行速度会非常慢。
更简便的实现方案
这个需求本质是找无向图的连通分量:每个文件是节点,每对匹配是边,同一个连通分量内的文件就是内容重复的一组文件。用并查集(DSU)可以非常高效的完成这个分组需求,代码逻辑简洁,还能覆盖所有边界情况:
class DSU: def __init__(self, elements): self.parent = {e: e for e in elements} # 查找根节点,带路径压缩优化 def find(self, x): if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) return self.parent[x] # 合并两个节点所在的集合 def union(self, x, y): root_x = self.find(x) root_y = self.find(y) if root_x != root_y: self.parent[root_y] = root_x # 处理流程 # 1. 收集所有出现过的文件名 all_files = set() for file_a, file_b in _data: all_files.add(file_a) all_files.add(file_b) # 2. 初始化并查集,合并所有匹配对 dsu = DSU(all_files) for file_a, file_b in _data: dsu.union(file_a, file_b) # 3. 按根节点分组,得到最终结果 groups = {} for file in all_files: root = dsu.find(file) if root not in groups: groups[root] = [] groups[root].append(file) # self.__map 就是所有重复文件分组的列表 self.__map = list(groups.values())
如果需要转成你示例里的分号分隔格式,遍历self.__map做字符串拼接即可:
result_str = [";".join(group) for group in self.__map]
内容的提问来源于stack exchange,提问作者Erik
相关产品推荐
相关产品推荐

