我在一个编码挑战中遇到了这个问题,尽管由于时间限制和对python的陌生,我当时无法解决这个问题。我现在已经试着解决了。但我想知道是否有更简单有效的方法来解决这个问题。你知道吗
config_file=[ \
"[__Box1A,Box1B__]", \
"portA:enabled=true", \
"portB:vlan=10", \
"portC:vlan=200", \
"[__Box2__]", \
"portA:poe=false", \
"portB:speed=100mbps",\
"[__Box3__]", \
"portA:use_lld=false", \
]
port_mappings=[ \
"[__Box1A,Box1B__]", \
"portA:Eth1/1", \
"portB:Eth1/2", \
"portC:Eth1/3", \
"[__Box3__]", \
"portA:Eth3/1", \
"[__Box2__]", \
"portA:Eth2/1", \
"portB:Eth2/2",\
]
给定2个列表作为配置文件和端口映射,结果数组如下所示。你知道吗
result_file=[ \
"[__Box1A,Box1B__]", \
"Eth1/1:enabled=true", \
"Eth1/2:vlan=10", \
"Eth1/3:vlan=200", \
"[__Box2__]", \
"Eth2/1:poe=false", \
"Eth2/2:speed=100mbps",\
"[__Box3__]", \
"Eth3/1:use_lld=false", \
]
A1dict2={}
for item in config_file:
if item.startswith('[_'):
key1=item
dict1={}
A1dict2[key1]=dict1
else:
sitem=re.split(':',item)
dict1[sitem[0]]=sitem[1]
print A1dict2
A2dict2={}
for item in port_mappings:
if item.startswith('[_'):
key1=item
dict1={}
A2dict2[key1]=dict1
else:
sitem=re.split(':',item)
dict1[sitem[0]]=sitem[1]
print A2dict2
A3dict2={}
dict3 = {}
for key in A1dict2:
tmpdict = {}
for key_child, item in A1dict2[key].iteritems():
tmpdict[A2dict2[key][key_child]] = item
dict3[key] = tmpdict
newlist=[]
for key,value in dict3.iteritems():
newlist.append(key)
for j in dict3[key].items():
x=map(str,j)
newlist.append(":".join(x))
print newlist
+1关于Code Review的建议,你的方式看起来不错,这里少了几行:
结果:
相关问题 更多 >
编程相关推荐