考虑一系列集合:
>>> [{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}
但是将它们作为列表或生成器表达式传递会导致 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'
为什么会发生,有哪些解决方案?