本文实例讲述了Python将多个映射合并为单个映射的方法。分享给大家供大家参考,具体如下:
问题:在逻辑上将多个字典或映射合并为一个单独的映射结构,以此执行某些特定的操作,比如查找值或者检查键是否存在
解决方案:利用collections
模块中的ChainMap
类
ChainMap
可接受多个映射然后在逻辑上使它们表现为一个单独的映射结构。这些映射在字面上并不会合并在一起。相反,ChainMap
只是简单地维护一个记录底层映射关系的列表,然后重定义常见的字典操作来扫描这个列表。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
# example.py
#
# Example of combining dicts into a chainmap
a = { 'x' : 1 , 'z' : 3 }
b = { 'y' : 2 , 'z' : 4 }
# (a) Simple example of combining
from collections import ChainMap
c = ChainMap(a,b) #如果有重复的键,那么会采用第一个映射中所对应的值。
print (c[ 'x' ]) # Outputs 1 (from a)
print (c[ 'y' ]) # Outputs 2 (from b)
print (c[ 'z' ]) # Outputs 3 (from a)
# Output some common values
print ( 'len(c):' , len (c))
print ( 'c.keys():' , list (c.keys()))
print ( 'c.values():' , list (c.values()))
# Modify some values
c[ 'z' ] = 10
c[ 'w' ] = 40
print ( "a:" , a)
del c[ 'x' ]
print ( "a:" , a)
# Example of stacking mappings (like scopes)
values = ChainMap()
values[ 'x' ] = 1
# Add a new mapping
values = values.new_child()
values[ 'x' ] = 2
# Add a new mapping
values = values.new_child()
values[ 'x' ] = 3
print (values)
print (values[ 'x' ])
# Discard last mapping
values = values.parents
print (values)
print (values[ 'x' ])
# Discard last mapping
values = values.parents
print (values)
print (values[ 'x' ])
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
>>> = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = RESTART = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
>>>
1
2
3
len (c): 3
c.keys(): [ 'y' , 'x' , 'z' ]
c.values(): [ 2 , 1 , 3 ]
a: { 'x' : 1 , 'z' : 10 , 'w' : 40 }
a: { 'z' : 10 , 'w' : 40 }
ChainMap({ 'x' : 3 }, { 'x' : 2 }, { 'x' : 1 })
3
ChainMap({ 'x' : 2 }, { 'x' : 1 })
2
ChainMap({ 'x' : 1 })
1
>>>
|
另外ChainMap操作的是原始字典,可以避免一些令人不悦的行为,例如其中任何一个原始字典的修改无法反应到合并后的字典中。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
>>> a = { 'x' : 1 , 'z' : 3 }
>>> b = { 'y' : 2 , 'z' : 4 }
>>> merged = ChainMap(a,b)
>>> merged
ChainMap({ 'x' : 1 , 'z' : 3 }, { 'y' : 2 , 'z' : 4 })
>>> merged[ 'x' ]
1
>>> a[ 'x' ] = 55
>>> merged[ 'x' ]
55
>>> merged
ChainMap({ 'x' : 55 , 'z' : 3 }, { 'y' : 2 , 'z' : 4 })
>>>
|
(代码摘自《Python Cookbook》)
希望本文所述对大家Python程序设计有所帮助。
原文链接:http://www.cnblogs.com/apple2016/p/5751301.html