密度聚类 多个集合求交集 汇总 python

#定义合并函数:将有共同核心点的临时聚类簇合并

test_list_set = [{1,2,3},{3,4,5},{10,12,13},{4,5,8},{13,15},{7,8},{20,22}] result = [] for index, t0 in enumerate(test_list_set): print(t0) group = set() for index, t1 in enumerate(test_list_set[index-1:]): if t0 & t1: group = group | t0 | t1 if (not result) and group: result.append(group) else: for index,r in enumerate(result): flag = 0 if r & group: result[index] = group|r flag = 1 break if (not flag) and group: result.append(group)
#定义合并函数:将有共同核心点的临时聚类簇合并
def mergeSets(list_set):
    result = []
    while  len(list_set)>0 :
        cur_set = list_set.pop(0)
        intersect_idxs = [i for i in list(range(len(list_set)-1,-1,-1)) if cur_set&list_set[i]]
        while  intersect_idxs :
            for idx in intersect_idxs:
                cur_set = cur_set|list_set[idx]

            for idx in intersect_idxs:
                list_set.pop(idx)
                
            intersect_idxs = [i for i in list(range(len(list_set)-1,-1,-1)) if cur_set&list_set[i]]
        
        result = result+[cur_set]
    return result

# 测试mergeSets效果
test_list_set = [{1,2,3},{3,4,5},{10,12,13},{4,5,8},{13,15},{7,8},{20,22}]
print(mergeSets(test_list_set))
[{1, 2, 3, 4, 5, 7, 8}, {10, 12, 13, 15}, {20, 22}]
posted @ 2021-12-08 16:28  cup_leo  阅读(64)  评论(0编辑  收藏  举报