小编Ama*_*eki的帖子

如何编写一个 python3 函数来合并两个集合列表,以便输出列表具有两个输入集中都存在的元素集合?

我有两个集合列表,比方说: [{1, 2, 3}, {4, 5}, {6, 7}] 和 [{1, 2}, {3, 4}, {5, 6, 7}]

列表中没有集合具有相同的元素,并且两个列表中所有集合的总和相同。该函数应检查两个列表中的集合是否具有相同的元素。如果有一些差异,请将它们放在另一组中。

所以上面的例子应该返回:[{1, 2}, {3}, {4}, {5}, {6, 7}]

我处理大型集合,因此我需要此功能尽可能有效。

这是示例代码以及我希望它如何工作:

def mergeSets(x, y):
    out = set()
    for i in x:
        out = out.union(i)
        # this allows me to get the set of all elements but here where my mind stops working
        # the problem sounds simple but thinking hours I can not think of good algorythm for this       issue :(
        # I found set.intersection() …
Run Code Online (Sandbox Code Playgroud)

python merge set time-complexity data-structures

1
推荐指数
1
解决办法
119
查看次数

标签 统计

data-structures ×1

merge ×1

python ×1

set ×1

time-complexity ×1