为什么 Python 的 dict.keys() 返回一个列表而不是一个集合?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13886129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:50:42  来源:igfitidea点击:

Why does Python's dict.keys() return a list and not a set?

pythonpython-2.x

提问by oneself

I would've expected Python's keys method to return a set instead of a list. Since it most closely resembles the kind of guarantees that keys of a hashmap would give. Specifically, they are unique and not sorted, like a set. However, this method returns a list:

我希望 Python 的 keys 方法返回一个集合而不是一个列表。因为它最类似于哈希映射的键所提供的那种保证。具体来说,它们是唯一的并且没有排序,就像一个集合。但是,此方法返回一个列表:

>>> d = {}
>>> d.keys().__class__
<type 'list'>

Is this just a mistake in the Python API or is there some other reason I am missing?

这只是 Python API 中的一个错误还是我遗漏了其他一些原因?

采纳答案by NPE

One reason is that dict.keys()predates the introduction of sets into the language.

一个原因是它dict.keys()早于将集合引入语言。

Note that the return type of dict.keys()has changed in Python 3: the function now returns a "set-like" viewrather than a list.

请注意,dict.keys()Python 3中的返回类型已更改:该函数现在返回“类似集合”的视图而不是列表。

For set-like views, all of the operations defined for the abstract base class collections.abc.Setare available (for example, ==, <, or ^).

对于类似集合的视图,为抽象基类定义的所有操作collections.abc.Set都可用(例如==<、 或^)。