集合和视图的区别 [英] Difference between a set and a view

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

问题描述

我已经学习 Python 大约一个多月了,我遇到了关于视图和集合的讨论.我正在使用的书 Learning Python 说视图是可迭代的,并且它们的对象的顺序与字典的顺序相同,但视图也支持集合操作.

I've been learning Python for about over a month, and I ran into a discussion about views and sets. The book I'm using, Learning Python, says that views are iterables and have their objects in the same order that the dictionary does, but views also supports set operations.

在我看来,他们可以做所有系列能做的事情.它看起来像鸭子,叫起来像鸭子,并且允许像鸭子一样进行集合操作.为什么集合和视图是分开的对象类型?

It seems to me that they can do everything sets do. It looks like a duck, quacks like a duck, and allow set operations like a duck. Why are sets and views then separate types of objects?

此外,我搜索了设置查看 Python 差异"以查找重复的问题,但找不到任何问题.

Also, I searched 'Set View Python Difference' to look for duplicate questions and couldn't find any.

推荐答案

只有 dict.keys() 字典视图总是是一个集合(只要它表现得像一套,但可以实时查看字典).

Only the dict.keys() dictionary view is always a set (insofar that it behaves like a set, but one with a live view of the dictionary).

dict.values() 视图从不是一个集合,因为不能保证值是唯一的,也不能保证是可散列的(要求套).您还必须在创建值字典视图时预先计算所有哈希值,这是一项可能非常昂贵的操作.在这种情况下,您始终可以使用显式 set(dictionary.values()).

The dict.values() view is never a set, as the values cannot be guaranteed to be unique and the are also not guaranteed to be hashable (a requirement for sets). You'd also have to calculate all hashes up-front the moment you create the values dictionary view, a potentially very expensive operation. You can always use an explicit set(dictionary.values()) in that case.

剩下的 dict.items() 视图,它主要是一个集合,前提是所有值都是可散列的;那是因为当您从视图创建交集或联合或其他新集合时,您必须 生成一个新的 set 对象,这要求整个键值对是可散列的;在这种情况下,您不能再保证只有键是唯一的.

That leaves the dict.items() view, which is mostly a set, provided all values are hashable; that's because when you create an intersection or union or other new set from the view, you have to produce a new set object, which requires that the whole key-value pair is hashable; you can no longer guarantee that just the keys will be unique in such cases.

另请参阅字典视图对象文档.

这篇关于集合和视图的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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