如何在Python的集合列表中找到联合?

Rav*_*vit 26 python list set python-3.x set-union

这是输入:

x = [{1, 2, 3}, {2, 3, 4}, {3, 4, 5}]
Run Code Online (Sandbox Code Playgroud)

输出应该是:

{1, 2, 3, 4, 5}
Run Code Online (Sandbox Code Playgroud)

我尝试使用,set().union(x)但这是我得到的错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
Run Code Online (Sandbox Code Playgroud)

vau*_*tah 34

签名set.unionunion(other, ...).从列表中解压缩集:

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

  • set().union(*x) 适用于空列表 (7认同)
  • 警告:不要在空列表上工作 (5认同)