python ChainMap管理用法实例讲解
作者:小妮浅浅 时间:2022-05-01 19:02:22
说明
1、ChainMap的主要用例是提供一种有效的方法来管理多个范围或上下文,并处理重复键的访问优先级。
2、当有多个存储重复键的字典访问它们的顺序时,这个功能非常有用。
在ChainMap文档中找到一个经典的例子,它模拟Python如何分析不同命名空间中的变量名称。
当Python搜索名称时,它会依次搜索当地、全局和内置的功能域,直到找到目标名称。Python作用域是将名称映射到对象的字典。
为了模拟Python的内部搜索链,可以使用链映射。
实例
>>> import builtins
>>> # Shadow input with a global name
>>> input = 42
>>> pylookup = ChainMap(locals(), globals(), vars(builtins))
>>> # Retrieve input from the global namespace
>>> pylookup["input"]
42
>>> # Remove input from the global namespace
>>> del globals()["input"]
>>> # Retrieve input from the builtins namespace
>>> pylookup["input"]
<built-in function input>
知识点扩展:
ChainMap类管理的是一个字典序列,并按其出现的顺序搜索以查找与键关联的值。ChainMap提供了一个很好的“上下文”容器,因此可以把它看成一个栈,栈增长时发生变更,栈收缩时这些变更被丢弃。
下面,我们来看看其基本的使用规则:
import collections
a = {"a": "A", "c": "c", }
b = {"b": "B", "c": "D", }
col = collections.ChainMap(a, b)
# 和普通字典一样访问
print(col["a"])
print(list(col.keys()), list(col.values()))
for key, value in col.items():
print(key, value)
可以看到,在相同的key值情况下,只有子映射a的值。这也就是说明ChainMap是按子映射传递到构造函数的顺序来搜索这些子映射。
来源:https://www.py.cn/jishu/jichu/32731.html
标签:python,ChainMap
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Django中URL视图函数的一些高级概念介绍
2021-04-14 13:35:21
隐藏你的.php文件的实现方法
2023-10-20 22:58:01
numpy中的随机打乱数据方法np.random.shuffle解读
2023-05-19 08:26:53
Python seek()和tell()函数的具体使用
2023-12-07 20:59:39
![](https://img.aspxhome.com/file/2023/2/67242_0s.gif)
如何设计注册激活邮件
2010-01-12 13:14:00
![](https://img.aspxhome.com/file/UploadPic/20101/12/2010-01-03_163629-89s.png)
DreamWeaver操作超级技巧大全
2008-10-03 20:50:00
Golang中goroutine和channel使用介绍深入分析
2023-07-07 16:51:48
解析Python的缩进规则的使用
2022-11-27 10:14:16
Django+Celery实现定时任务的示例
2023-07-27 19:48:18
![](https://img.aspxhome.com/file/2023/4/61704_0s.png)
Python matplotlib模块及柱状图用法解析
2023-11-24 01:04:33
![](https://img.aspxhome.com/file/2023/5/117335_0s.png)
python求pi的方法
2023-04-04 06:49:17
win10+anaconda安装yolov5的方法及问题解决方案
2022-02-03 10:31:58
![](https://img.aspxhome.com/file/2023/4/83854_0s.png)
使用Python开发游戏运行脚本成功调用大漠插件
2021-03-09 21:05:53
![](https://img.aspxhome.com/file/2023/9/99679_0s.png)
Python实现字典按照value进行排序的方法分析
2022-11-03 04:27:27
ASP在线生成电话图片程序
2007-10-06 23:06:00
![](https://img.aspxhome.com/file/UploadPic/200710/6/200710623165632s.gif)
一文学会VSCode使用python
2022-07-26 16:06:46
![](https://img.aspxhome.com/file/2023/5/126925_0s.jpg)
利用Python如何生成hash值示例详解
2022-02-28 23:29:25
python超参数优化的具体方法
2022-01-04 22:28:31
python+pandas分析nginx日志的实例
2021-03-13 12:51:22
![](https://img.aspxhome.com/file/2023/0/98810_0s.jpg)
在Python的Flask中使用WTForms表单框架的基础教程
2023-05-10 05:20:08
![](https://img.aspxhome.com/file/2023/6/90746_0s.png)