如何在Python中查找集合列表的并集?

57

这是输入内容:

x = [{1, 2, 3}, {2, 3, 4}, {3, 4, 5}]

输出结果应该为:

{1, 2, 3, 4, 5}

我试图使用set().union(x),但是出现了这个错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
1个回答

86

set.union 的签名是 union(other, ...)。从列表中拆分集合:

In [6]: set.union(*x)
Out[6]: {1, 2, 3, 4, 5}

8
警告:不要在空列表上操作。 - David Froger
12
set().union(*x) 在空列表上有效。 - Jethro Yu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接