简体   繁体   English

python如何合并一个集合列表并将它们作为一个集合返回?

[英]How can python merges a list of sets and return them as a set?

I have a list of sets like this:我有一个这样的集合列表:

set_list = [{1, 2, 3}, {4, 5, 1, 6}, {2, 3, 6}, {1, 5, 8}]

Now I want to merge all of the sets together and return a set of all sets like this:现在我想将所有集合合并在一起并返回一组所有集合,如下所示:

final_set = {1, 2, 3, 4, 5, 6, 8}

I have used this code but it is not working correctly:我已经使用了此代码,但它无法正常工作:

tmp_list = []
final_set = set(tmp_list.append(elem) for elem in set_list)

What should I do?我该怎么办?

You can use unpacking with set.union for a clean one-liner.您可以使用set.union进行拆包以获得干净的单行。

>>> set.union(*set_list)
{1, 2, 3, 4, 5, 6, 8}

You can use reduce functio n from functools module .您可以使用functools模块中的reduce函数

>>> from functools import reduce
>>> set_list = [{1,2,3}, {4,5,1,6}, {2,3,6}, {1,5,8}]
>>> reduce(lambda x, y: x | y, set_list)
{1, 2, 3, 4, 5, 6, 8}

You can iterate over the list and create a union of all sets:您可以遍历列表并创建所有集合的并集:

new_set = set()
for i in set_list:
    new_set =  set.union(new_set, i)
print(new_set)

Output:输出:

{1, 2, 3, 4, 5, 6, 8}

You might do that using comprehension as follows你可以使用理解来做到这一点,如下所示

set_list = [{1, 2, 3}, {4, 5, 1, 6}, {2, 3, 6}, {1, 5, 8}]
final_set = set(elem for sub in set_list for elem in sub)
print(final_set)

output输出

{1, 2, 3, 4, 5, 6, 8}

Explanation: this is simple adaptation of list-of-lists flattener comprehension which can be used as set s are iterable.解释:这是列表列表扁平化理解的简单改编,可以用作set是可迭代的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM