考虑一系列集合:
>>> [{n, 2*n} for n in range(5)]
[{0}, {1, 2}, {2, 4}, {3, 6}, {8, 4}]将它们直接传递到联合方法中会产生正确的结果:
>>> set().union({0}, {1, 2}, {2, 4}, {3, 6}, {8, 4})
{0, 1, 2, 3, 4, 6, 8}但将它们作为列表或生成器表达式传递会导致TypeError:
>>> 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'为什么会发生这种情况?有哪些解决方案?
发布于 2018-08-16 15:33:39
出现此错误的原因是set.union()需要一个或多个集合(即set.union(oneset, anotherset, andathirdone)),而不是list或生成器。
解决方案是解压列表或生成器:
>>> set().union( *({n, 2*n} for n in range(5)) )
{0, 1, 2, 3, 4, 6, 8}发布于 2018-08-16 16:08:53
以下是无需创建列表即可联合多个集合的方法
s = set()
for n in range(5):
s = s.union({n, 2*n})https://stackoverflow.com/questions/51871836
复制相似问题