为什么dict_items对象不支持索引? [英] Why do dict_items objects not support indexing?
问题描述
我知道您可以将dict_items
转换为list
以允许项目索引.但是我不知道为什么不允许直接进行此操作.是因为dict_items
对象是生成器吗?如果是这样,当我看到
I know that you can cast dict_items
into a list
to allow item indexing. But I do not know why this operation is not allowed directly. Is it because dict_items
objects are generators? If so, when I'm seeing
>>> {"foo": "bar", "baz": "qux"}.items()
dict_items([('foo', 'bar'), ('baz', 'qux')])
在调用repr
时,Python是否正在评估我的生成器?
is Python evaluating my generator when repr
is called?
推荐答案
dict_items
不支持索引编制,因为这些对象旨在像集合一样,集合也不支持编制索引.
dict_items
do not support indexing because these objects are intended to be set-like, and sets do not support indexing.
它们确实以其他方式发出类似嘎嘎的声音:
They do quack like sets in other ways:
>>> d1 = {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
>>> d2 = {'k2': 'v2', 'k3': 'not v3'}
>>> d1.items() & d2.items()
{('k2', 'v2')}
>>> d1.items() | d2.items()
{('k1', 'v1'), ('k2', 'v2'), ('k3', 'not v3'), ('k3', 'v3')}
如果任何值不可散列,则将失去使用set操作处理字典项视图的能力.
If any value is not hashable, you lose the ability to treat the dict items views with set operations.
为dict_items
视图提供索引支持是不明智的,因为dict在Python 3.7+之前没有排序,因此无法很好地定义访问第0个"项目.即使在Python 3.7中,有一个 用于索引的合理顺序(即插入顺序),以 O(1)的复杂度实现它也是不平凡的,因此不受支持. 不成文的规则"是索引应该是固定时间的操作(因为它适用于列表,元组,字典,字符串-
It is not sensible to give indexing support to dict_items
views, because the dict does not have an ordering until Python 3.7+, so accessing "the 0th" item would not be well-defined. Even in Python 3.7, where there is a sensible ordering to use for indexing (i.e. the insertion order), it is non-trivial to implement this with O(1) complexity, so it's not supported. The "unwritten rule" is that indexing should be constant-time operation (as it is for list, tuple, dict, str - see here).
这篇关于为什么dict_items对象不支持索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!