如何用Python查找YAML文件中同类型下的重复IP
查找同一类型下的重复IP
原始YAML数据
- ip: 1.1.1.1 status: Active type: 'typeA' - ip: 1.1.1.1 status: Disabled type: 'typeA' - ip: 2.2.2.2 status: Active type: 'typeC' - ip: 3.3.3.3 status: Active type: 'typeB' - ip: 3.3.3.3 status: Active type: 'typeC' - ip: 2.2.2.2 status: Active type: 'typeC' -
需求说明
找出同一type下重复出现的IP,即IP与type的组合重复的条目,忽略status字段差异。
实现脚本(Python)
import yaml from collections import defaultdict # 读取YAML文件 with open('target.yaml', 'r', encoding='utf-8') as f: entries = yaml.safe_load(f) # 统计IP+type组合的出现次数 record_counts = defaultdict(int) for item in entries: if not item: # 跳过空条目 continue key = (item['ip'], item['type']) record_counts[key] += 1 # 输出重复项 for (ip, typ), count in record_counts.items(): if count > 1: print(f"IP {ip},{typ} 重复")
运行结果
IP 1.1.1.1,typeA 重复 IP 2.2.2.2,typeC 重复
内容的提问来源于stack exchange,提问作者Saeed
相关产品推荐
相关产品推荐

