Python union of sets raises TypeError

五迷三道 提交于 2019-12-12 20:18:10

问题


Consider a sequence of sets:

>>> [{n, 2*n} for n in range(5)]
[{0}, {1, 2}, {2, 4}, {3, 6}, {8, 4}]

Passing them directly into the union method yields the correct result:

>>> set().union({0}, {1, 2}, {2, 4}, {3, 6}, {8, 4})
{0, 1, 2, 3, 4, 6, 8}

But passing them as a list or generator expression results in a 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'

Why does it happen and what are some solutions?


回答1:


The reason for this error is that set.union() expects one or more sets (ie set.union(oneset, anotherset, andathirdone)), not a list nor generator.

The solution is to unpack your list or generator:

>>> set().union( *({n, 2*n} for n in range(5)) )
{0, 1, 2, 3, 4, 6, 8}



回答2:


Here's way to union multiple sets without creating a list

s = set()

for n in range(5): 
    s = s.union({n, 2*n})


来源:https://stackoverflow.com/questions/51871836/python-union-of-sets-raises-typeerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!