Python 集并集引发 TypeError
Python union of sets raises TypeError
考虑一组序列:
>>> [{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)
),而不是 list
或生成器。
解决方案是解压您的列表或生成器:
>>> set().union( *({n, 2*n} for n in range(5)) )
{0, 1, 2, 3, 4, 6, 8}
这是在不创建列表的情况下联合多个集合的方法
s = set()
for n in range(5):
s = s.union({n, 2*n})
考虑一组序列:
>>> [{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)
),而不是 list
或生成器。
解决方案是解压您的列表或生成器:
>>> set().union( *({n, 2*n} for n in range(5)) )
{0, 1, 2, 3, 4, 6, 8}
这是在不创建列表的情况下联合多个集合的方法
s = set()
for n in range(5):
s = s.union({n, 2*n})