{frozenset()} 中的 set() 如何/为什么工作? [英] How/why does set() in {frozenset()} work?

查看:19
本文介绍了{frozenset()} 中的 set() 如何/为什么工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使集合是不可散列的,其他集合中的成员资格检查仍然有效:

<预><代码>>>>{frozenset()} 中的 set()真的

我期望 TypeError: unhashable type: 'set',与 Python 中的其他行为一致:

<预><代码>>>>set() in {} # 在检查字典时不起作用类型错误:不可散列的类型:设置">>>{} in {frozenset()} # 查找其他不可散列的类型不起作用类型错误:不可散列的类型:'dict'

那么,其他集合中的集合成员资格是如何实现的?

解决方案

最后一行 sets 的文档讨论了这个:

<块引用>

注意,elem 参数__contains__(), remove()丢弃()方法可以是 set.支持搜索等效项frozenset,从elem创建一个临时的.

Even though sets are unhashable, membership check in other set works:

>>> set() in {frozenset()}
True

I expected TypeError: unhashable type: 'set', consistent with other behaviours in Python:

>>> set() in {}  # doesn't work when checking in dict
TypeError: unhashable type: 'set'
>>> {} in {frozenset()}  # looking up some other unhashable type doesn't work
TypeError: unhashable type: 'dict'

So, how is set membership in other set implemented?

解决方案

The last line of the documentation for sets discusses this:

Note, the elem argument to the __contains__(), remove(), and discard() methods may be a set. To support searching for an equivalent frozenset, a temporary one is created from elem.

这篇关于{frozenset()} 中的 set() 如何/为什么工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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