python中的迭代式听写

2024-10-04 01:22:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个编码挑战中遇到了这个问题,尽管由于时间限制和对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

Tags: keyinfalseforitemeth1key1vlan
1条回答
网友
1楼 · 发布于 2024-10-04 01:22:07

+1关于Code Review的建议,你的方式看起来不错,这里少了几行:

from collections import OrderedDict
config_dict = OrderedDict()
port_map_dict = OrderedDict()

def map_items(list_of_items, ordered_dict):
    for i in list_of_items:
        if i.startswith('[__Box'):
            current = i
            ordered_dict[i] = OrderedDict()
        else:
            port, option = i.split(':')
            ordered_dict[current][port] = option

map_items(config_file, config_dict)
map_items(port_mappings, port_map_dict)

result_file = []
for box, items in config_dict.iteritems():
    result_file.append(box)
    for port, value in items.iteritems():
        result_file.append('{}:{}'.format(port_map_dict[box][port], value))

结果:

In [47]: result_file
Out[47]:
['[__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']

相关问题 更多 >