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

如何用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 01:54:54