使用未排序接口列表搜索配置文件时如何保持原顺序?
保持接口列表原顺序匹配描述信息的解决方法
问题背景
现有一组未按数值排序的接口列表:
Bundle-Ether30.1076 Bundle-Ether30.692 Bundle-Ether30.839 Bundle-Ether30.43
从Rancid仓库拉取配置文件后,使用嵌套for循环或列表推导式搜索这些接口的描述信息时,结果会按配置文件中的接口顺序输出,无法保持原列表的顺序。
尝试的嵌套循环代码:
interfacedescription = [] for line in config: for each in interfacelist: if each in line and 'description' in line: interfacedescription.append(line.split('description ')[-1])
尝试的列表推导式代码:
interfacedescription = [x.split('description ')[-1] for x in config if any(y in x for y in config) and 'description' in x] for interface, description in zip(interfacelist, interfacedescription): print(interface+'\t\t'+description)
期望输出保持原接口列表的顺序:
Bundle-Ether30.1076 Bundle-Ether30.1076 description Bundle-Ether30.692 Bundle-Ether30.692 description Bundle-Ether30.839 Bundle-Ether30.839 description Bundle-Ether30.43 Bundle-Ether30.43 description
解决方法
核心思路是先将配置文件中的所有接口与对应描述构建成键值对字典,再按原接口列表的顺序从字典中提取对应描述,即可保证输出顺序与原列表一致。
步骤1:构建接口-描述映射字典
遍历配置文件,先定位接口行,再记录该接口对应的描述信息:
# 初始化映射字典 interface_desc_map = {} current_interface = None for line in config: # 匹配配置中的接口定义行(需根据实际配置格式调整匹配规则) stripped_line = line.strip() if stripped_line.startswith('interface'): # 提取接口名称(假设行格式为 "interface Bundle-Ether30.xxx") current_interface = stripped_line.split()[-1] # 当已定位到接口,且当前行包含描述信息时,记录映射 elif current_interface and 'description' in stripped_line: # 提取描述内容,去除多余空白 desc_content = stripped_line.split('description ')[-1].strip() interface_desc_map[current_interface] = desc_content
步骤2:按原列表顺序提取描述
基于构建好的字典,遍历原接口列表逐个获取对应描述:
# 按原接口列表顺序生成描述列表,无描述时填充默认值 interfacedescription = [interface_desc_map.get(iface, "无匹配描述") for iface in interfacelist] # 格式化输出结果 for interface, description in zip(interfacelist, interfacedescription): print(f"{interface}\t\t{description}")
原理说明
之前的代码是遍历配置文件的每一行,找到匹配的接口描述就添加到结果列表,因此结果顺序由配置文件中的接口顺序决定。而通过字典预存所有接口的描述映射后,按原接口列表的顺序去字典中取值,就能严格保持原列表的顺序。
内容的提问来源于stack exchange,提问作者KellyH
相关产品推荐
相关产品推荐

