[英]Matching a substring from a substring list in a list of strings
[英]Return matching value from substring in a list against dictionary containing substring
我有一个字典列表,如下所示。
[{'cvid': '642', 'switch': '015ABC003999FR', 'uni': '5'},
{'cvid': '523', 'switch': '017ABC001230FR', 'uni': '5'},
{'cvid': '43', 'switch': '017ABC001231FR', 'uni': '2'},
{'cvid': '45', 'switch': '500ABC005437FR', 'uni': '3'}]
我还有一个包含如下值的列表。
[['000015ABC003999CIRC'], ['000017ABC001230CIRC'], ['000017ABC001231CIRC'], ['000015ABC000249CIRC'], ['000500ABC005437CIRC']]
我希望能够从 {'switch':'015ABC003999FR'} 值中提取一个子字符串,并将值 000015ABC003999CIRC 返回并附加到与 {'circ':'000015ABC003999CIRC'} 相同的字典中。
我一直无法找到接近该场景的示例。 是否有可能像字典的 015ABC003999 的正则表达式然后也匹配列表的正则表达式? 我认为另一种选择是创建在前面添加零的值并用 CIRC 替换 FR,但我宁愿与列表匹配作为一种验证。
然后我会使用字典来填充类似于下面的配置
print('cfm service delete service ' + dic['switch'])
print('cfm mep create service ' + dic['circ'] + ' port ' + dic['uni'] + ' type up vlan ' + dic['cvid'] + ' mepid 3')
您可以在两个 for 循环中迭代这两个循环,看起来您需要在使用in
检查子字符串之前删除switch
值的最后两个字符:
import json
data = [
{
"cvid": "642",
"switch": "015ABC003999FR",
"uni": "5"
},
{
"cvid": "523",
"switch": "017ABC001230FR",
"uni": "5"
},
{
"cvid": "43",
"switch": "017ABC001231FR",
"uni": "2"
},
{
"cvid": "45",
"switch": "500ABC005437FR",
"uni": "3"
}
]
lst = [['000015ABC003999CIRC'], ['000017ABC001230CIRC'], ['000017ABC001231CIRC'],
['000015ABC000249CIRC'], ['000500ABC005437CIRC']]
for d in data:
switch_val_without_last_2_ch = d["switch"][:-2]
for sub_lst in lst:
val = sub_lst[0]
if switch_val_without_last_2_ch in val:
d["circ"] = val
break
print(json.dumps(data, indent=2, sort_keys=False))
for dic in data:
print(f'cfm service delete service {dic["switch"]}')
print(f'cfm mep create service {dic["circ"]} port {dic["uni"]} type up vlan {dic["cvid"]} mepid 3')
输出:
[
{
"cvid": "642",
"switch": "015ABC003999FR",
"uni": "5",
"circ": "000015ABC003999CIRC"
},
{
"cvid": "523",
"switch": "017ABC001230FR",
"uni": "5",
"circ": "000017ABC001230CIRC"
},
{
"cvid": "43",
"switch": "017ABC001231FR",
"uni": "2",
"circ": "000017ABC001231CIRC"
},
{
"cvid": "45",
"switch": "500ABC005437FR",
"uni": "3",
"circ": "000500ABC005437CIRC"
}
]
cfm service delete service 015ABC003999FR
cfm mep create service 000015ABC003999CIRC port 5 type up vlan 642 mepid 3
cfm service delete service 017ABC001230FR
cfm mep create service 000017ABC001230CIRC port 5 type up vlan 523 mepid 3
cfm service delete service 017ABC001231FR
cfm mep create service 000017ABC001231CIRC port 2 type up vlan 43 mepid 3
cfm service delete service 500ABC005437FR
cfm mep create service 000500ABC005437CIRC port 3 type up vlan 45 mepid 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.