You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python循环按条件生成字典列表 合并同前缀同VRF的描述字段

Python 网段前缀聚合代码修正方案

原代码问题分析

  • 语法错误:ip_addresses_all 列表中每个字典元素都缺少闭合的 },导致代码无法正常解析
  • 缩进错误:前缀匹配与新增的逻辑完全放在了IP遍历循环之外,仅会处理最后一个IP地址
  • 死循环诱因:遍历prefixes列表的同时向列表内追加元素,列表长度随遍历不断增长,导致循环永远无法终止
  • 逻辑错误:匹配规则错误,只要遇到任意一个不匹配的前缀就新增条目,会生成大量重复冗余数据

修正后代码

import ipaddress
from pprint import pprint

prefixes = []
# 补全原列表缺失的字典闭合括号,修正语法问题
ip_addresses_all = [
    {'address': '10.0.0.1/24', 'vrf': {'id': 31,'name': 'god_inet'}},
    {'address': '10.0.0.10/24', 'vrf': {'id': 33, 'name': 'for_test'}},
    {'address': '10.1.1.1/30', 'vrf': {'id': 8, 'name': 'ott_private_net'}},
    {'address': '10.1.1.2/30', 'vrf': {'id': 11,'name': 'ott_public_net'}},
    {'address': '10.10.0.129/30', 'vrf': None},
    {'address': '10.10.0.130/30', 'vrf': None},
    {'address': '10.10.0.137/30', 'vrf': None},
    {'address': '10.10.0.138/30', 'vrf': None}
]

for ip in ip_addresses_all:
    # 计算当前IP对应的网段前缀
    prefix = str(ipaddress.ip_network(ip['address'], strict=False))
    description_interface = ip['address']
    # 处理VRF信息
    if ip['vrf']:
        ip_vrf_name = ip['vrf']['name']
        ip_vrf_id = ip['vrf']['id']
    else:
        ip_vrf_name = 'null'
        ip_vrf_id = 'null'
    
    # 标记是否找到匹配的已有条目
    found = False
    for exist_item in prefixes:
        # 匹配规则:前缀相同 + VRF名称相同
        if exist_item['prefix'] == prefix and exist_item['vrf']['name'] == ip_vrf_name:
            # 描述不存在就追加
            if description_interface not in exist_item['prefix_description']:
                exist_item['prefix_description'].append(description_interface)
            found = True
            break
    # 没找到匹配条目就新增
    if not found:
        prefix_dict = {
            'prefix': prefix,
            'vrf': {'name': ip_vrf_name, 'id': ip_vrf_id},
            'prefix_description': [description_interface]
        }
        prefixes.append(prefix_dict)

pprint(prefixes)

输出结果

运行上述代码会得到符合要求的列表格式输出:

[{'prefix': '10.0.0.0/24',
  'prefix_description': ['10.0.0.1/24'],
  'vrf': {'id': 31, 'name': 'god_inet'}},
 {'prefix': '10.0.0.0/24',
  'prefix_description': ['10.0.0.10/24'],
  'vrf': {'id': 33, 'name': 'for_test'}},
 {'prefix': '10.1.1.0/30',
  'prefix_description': ['10.1.1.1/30'],
  'vrf': {'id': 8, 'name': 'ott_private_net'}},
 {'prefix': '10.1.1.0/30',
  'prefix_description': ['10.1.1.2/30'],
  'vrf': {'id': 11, 'name': 'ott_public_net'}},
 {'prefix': '10.10.0.128/30',
  'prefix_description': ['10.10.0.129/30', '10.10.0.130/30'],
  'vrf': {'id': 'null', 'name': 'null'}},
 {'prefix': '10.10.0.136/30',
  'prefix_description': ['10.10.0.137/30', '10.10.0.138/30'],
  'vrf': {'id': 'null', 'name': 'null'}}]

内容的提问来源于stack exchange,提问作者Dover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 05:48:04