问题描述
在Python 3.3中,类已添加到模块:
In Python 3.3 a ChainMap
class was added to the collections
module:
示例:
>>> from collections import ChainMap
>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 10, 'c': 11}
>>> z = ChainMap(y, x)
>>> for k, v in z.items():
print(k, v)
a 1
c 11
b 10
它的动机是,并由(no PEP
已创建)。
It was motivated by this issue and made public by this one (no PEP
was created).
据我所知,这是替换一个额外的字典,并使用 s。
As far as I understand, it is an alternative to having an extra dictionary and maintaining it with update()
s.
问题是:
-
ChainMap
封面有什么用途? - 有没有
ChainMap
的真实世界示例? - 是否用于切换到python3的第三方库?
- What use cases does
ChainMap
cover? - Are there any real world examples of
ChainMap
? - Is it used in third-party libraries that switched to python3?
奖金问题:有没有办法在Python2.x上使用它?
Bonus question: is there a way to use it on Python2.x?
我在由Raymond Hettinger发表的PyCon讲座喜欢将其添加到我的工具包,但是我不明白什么时候应该使用它。
I've heard about it in Transforming Code into Beautiful, Idiomatic Python
PyCon talk by Raymond Hettinger and I'd like to add it to my toolkit, but I lack in understanding when should I use it.
推荐答案
我喜欢@ b4hand的例子,实际上我曾经在过去使用过ChainMap类结构(但不是ChainMap本身)他提到的两个目的是:多层配置覆盖和可变堆栈/范围仿真。
I like @b4hand's examples, and indeed I have used in the past ChainMap-like structures (but not ChainMap itself) for the two purposes he mentions: multi-layered configuration overrides, and variable stack/scope emulation.
我想指出另外两个动机/优点/ code> ChainMap ,与使用dict-update循环相比,只存储最终版本:
I'd like to point out two other motivations/advantages/differences of ChainMap
, compared to using a dict-update loop, thus only storing the "final" version":
-
更多信息,因为ChainMap结构是分层的,它支持回答问题:我得到默认值,还是被覆盖的原始(默认)值?值被覆盖在什么级别(借用@ b4hand的配置示例:user-config或命令行覆盖)?使用简单的dict,回答这些问题所需的信息已经丢失。
More information: since a ChainMap structure is "layered", it supports answering question like: Am I getting the "default" value, or an overridden one? What is the original ("default") value? At what level did the value get overridden (borrowing @b4hand's config example: user-config or command-line-overrides)? Using a simple dict, the information needed for answering these questions is already lost.
速度折衷:假设您有 N每个层次最多只需$
M
,构建一个ChainMap就需要 O(N)
并且每个查找 O(N)
最坏情况[*],而使用更新循环构建dict使用 O(NM) code>和每个查找
O(1)
。这意味着,如果您经常构建并且每次只执行几次查找,或者如果 M
是大的,ChainMap的懒惰构造方法对您有利。
Speed tradeoff: suppose you have N
layers and at most M
keys in each, constructing a ChainMap takes O(N)
and each lookup O(N)
worst-case[*], while construction of a dict using an update-loop takes O(NM)
and each lookup O(1)
. This means that if you construct often and only perform a few lookups each time, or if M
is big, ChainMap's lazy-construction approach works in your favor.
[*](2)中的分析假设dict-access为 O(1)
,实际上平均而言是 O(1)
,最坏情况是 O(M)
。查看更多详情。
[*] The analysis in (2) assumes dict-access is O(1)
, when in fact it is O(1)
on average, and O(M)
worst case. See more details here.
这篇关于收藏的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!