考虑一系列集合:
>>> [{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/