多个列表根据交集进行合并

# -*- coding: utf-8 -*-#
# -------------------------------------------------------------------------------
# Name:         列表根据交集合并
# Author:       yunhgu
# Date:         2022/2/22 15:16
# Description: 
# -------------------------------------------------------------------------------
def merge_lists1(list_2d: list):
    """
    :param list_2d:二维列表
    :return:
    """
    sets = {}
    for lst in list_2d:
        s = set(lst)
        t = set()
        for x in s:
            if x in sets:
                t.update(sets.get(x))
            else:
                sets[x] = s
        for y in t:
            sets[y] = s
        s.update(t)
    result_list = []
    for s in sets.values():
        if list(s) not in result_list:
            result_list.append(list(s))
    return result_list


def merge_lists2(lists_2d: list):
    set_list = list(map(set, lists_2d))
    i, n = 0, len(set_list)
    while i < n - 1:
        for j in range(i + 1, n):
            if set_list[i].intersection(set_list[j]):
                set_list[i].update(set_list[j])
                del set_list[j]
                n -= 1
                break
        else:
            i += 1
    return [sorted(i) for i in set_list]


if __name__ == '__main__':
    data_list = [[1, 2], [4, 5], [1, 6], [2, 9]]
    print(merge_lists1(data_list))
    print(merge_lists2(data_list))

image

posted @ 2022-02-22 15:52  不能说的秘密  阅读(125)  评论(0编辑  收藏  举报