【发布时间】:2019-01-23 02:32:51
【问题描述】:
考虑一个集合序列:
>>> [{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'
为什么会发生,有什么解决办法?
【问题讨论】:
标签: python set generator-expression set-union