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

Python如何删除字典列表中源目顺序相反的重复网络连接条目

解决方案

核心思路是先统一提取链路两端的核心标识,再生成与源目顺序无关的唯一指纹实现去重,具体实现如下:

实现步骤

  1. 统一字段映射:兼容src/src_id、dst/dst_id两种键名,提取每个条目的两端核心信息(IP、ID、名称)
  2. 生成顺序无关指纹:将两个端点的信息排序后拼接为不可变元组,同一条物理链路正反条目生成的指纹完全一致
  3. 优先级控制:优先保留带有src_id/dst_id字段的条目,符合输出预期

代码示例

# 原始数据
raw_links = [
    {'ip_src': '2.2.2.2',
     'ip_dst': '1.1.1.1',
     'src_id': 43,
     'src_name': 'test1',
     'dst_id': 48,
     'dst_name': 'test2'},
    {'ip_src': '1.1.1.1',
     'ip_dst': '2.2.2.2',
     'src': 48,
     'src_name': 'test2',
     'dst': 43,
     'dst_name': 'test1'},
    {'ip_src': '4.4.4.4',
     'ip_dst': '3.3.3.3',
     'src_id': 41,
     'src_name': 'test1',
     'dst_id': 47,
     'dst_name': 'test2'},
    {'ip_src': '3.3.3.3',
     'ip_dst': '4.4.4.4',
     'src': 47,
     'src_name': 'test2',
     'dst': 41,
     'dst_name': 'test1'},
]

seen_links = set()
dedup_result = []
# 先排序,让带src_id的条目优先被处理,保证保留格式符合预期
sorted_raw = sorted(raw_links, key=lambda x: 0 if 'src_id' in x else 1)

for link in sorted_raw:
    # 兼容两种键名提取ID
    src_id = link.get('src_id') or link['src']
    dst_id = link.get('dst_id') or link['dst']
    # 提取两端核心信息三元组
    end_a = (link['ip_src'], src_id, link['src_name'])
    end_b = (link['ip_dst'], dst_id, link['dst_name'])
    # 排序后生成唯一指纹,消除源目顺序影响
    link_fingerprint = tuple(sorted([end_a, end_b]))
    
    if link_fingerprint not in seen_links:
        seen_links.add(link_fingerprint)
        dedup_result.append(link)

# 输出结果
for item in dedup_result:
    print(item)

输出结果

运行后得到的dedup_result完全符合预期:

[
    {'ip_src': '2.2.2.2',
     'ip_dst': '1.1.1.1',
     'src_id': 43,
     'src_name': 'test1',
     'dst_id': 48,
     'dst_name': 'test2'},
    {'ip_src': '4.4.4.4',
     'ip_dst': '3.3.3.3',
     'src_id': 41,
     'src_name': 'test1',
     'dst_id': 47,
     'dst_name': 'test2'}
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:00:00