Python 集合并集引发 TypeError

标签 python set generator-expression set-union

考虑一系列集合:

>>> [{n, 2*n} for n in range(5)]
[{0}, {1, 2}, {2, 4}, {3, 6}, {8, 4}]

将它们直接传递到 union 方法中会产生正确的结果:

>>> set().union({0}, {1, 2}, {2, 4}, {3, 6}, {8, 4})
{0, 1, 2, 3, 4, 6, 8}

但是将它们作为列表或生成器表达式传递会导致类型错误:

>>> set().union( [{n, 2*n} for n in range(5)] )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'

>>> set().union({n, 2*n} for n in range(5))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'

为什么会发生这种情况以及有哪些解决方案?

最佳答案

此错误的原因是 set.union() 需要一个或多个集合(即 set.union(oneset, anotherset, andathirdone)),而不是一个列表也不是生成器。

解决方案是解压列表或生成器:

>>> set().union( *({n, 2*n} for n in range(5)) )
{0, 1, 2, 3, 4, 6, 8}

关于Python 集合并集引发 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51871836/

相关文章:

c++ - 如何对一组对进行排序?

python - 使用列表理解将字符串转换为字典

python - numpy 已与 Anaconda 一起安装,但我收到 ImportError(DLL 加载失败 : The specified module could not be found)

c++ - 使用排序数组实现集合

python - 在 Python 中从 2 个列表中删除多个值,但只删除一次

python - Django 模板中对象价格的总和

python - 有没有办法在 Python 中构造惰性序列?

Python绘制两个不同长度的列表

python - 算法运行时迭代for循环分析

python - 如何将多个掩码应用于数组并计算每行的出现次数