Python的集合并集引发TypeError [英] Python union of sets raises TypeError

查看:117
本文介绍了Python的集合并集引发TypeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一组序列:

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

将它们直接传递给union方法会产生正确的结果:

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}

但是将它们作为列表或生成器表达式传递会导致TypeError:

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?

推荐答案

此错误的原因是set.union()需要一个或多个集合(即set.union(oneset, anotherset, andathirdone)),而不是list或生成器.

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}

这篇关于Python的集合并集引发TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆