【问题标题】:How can I find the union on a list of sets in Python? [duplicate]如何在 Python 的集合列表中找到并集? [复制]
【发布时间】:2015-09-24 00:41:04
【问题描述】:

这是输入:

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'

【问题讨论】:

    标签: python list python-3.x set set-union


    【解决方案1】:

    set.union 的签名是union(other, ...)。从您的列表中解压套装:

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

    【讨论】:

    • 警告:不要在空列表上工作
    • set().union(*x) 适用于空列表
    猜你喜欢
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    相关资源
    最近更新 更多