品易云推流 关闭
文章详情页
文章 > Python基础教程 > python中ChainMap如何实例化

python中ChainMap如何实例化

Python ChainMap

头像

小妮浅浅

2021-08-17 11:14:292188浏览 · 0收藏 · 0评论

说明

1、为了在Python代码中创建ChainMap,需要从类导入collections,然后调用。

2、类初始值设置项可以将零或多个映射作为参数。无参数,它初始化一个链式映射,里面有一个空字典。

使用不同的映射组合,ChainMap可以创建多个对象。每一种情况下,ChainMap都会返回输入映射的单个类似字典的视图。可以使用任何类型的映射,比如OrderedDict和defaultdict。

实例

>>> from collections import ChainMap
>>> from collections import OrderedDict, defaultdict
 
>>> # Use no arguments
>>> ChainMap()
ChainMap({})
 
>>> # Use regular dictionaries
>>> numbers = {"one": 1, "two": 2}
>>> letters = {"a": "A", "b": "B"}
 
>>> ChainMap(numbers, letters)
ChainMap({'one': 1, 'two': 2}, {'a': 'A', 'b': 'B'})
 
>>> ChainMap(numbers, {"a": "A", "b": "B"})
ChainMap({'one': 1, 'two': 2}, {'a': 'A', 'b': 'B'})
 
>>> # Use other mappings
>>> numbers = OrderedDict(one=1, two=2)
>>> letters = defaultdict(str, {"a": "A", "b": "B"})
>>> ChainMap(numbers, letters)
ChainMap(
    OrderedDict([('one', 1), ('two', 2)]),
    defaultdict(<class 'str'>, {'a': 'A', 'b': 'B'})
)

以上就是python中ChainMap的实例化方法,希望对大家有所帮助。更多Python学习指路:python基础教程

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图