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

如何在Python中按IP地址对特定结构列表的元素分组

按IP地址聚合分组输出的实现方法

问题描述

我有一个结构为[{key:[..,..]}]的列表,希望按IP地址对输出进行分组。现有列表my_list及遍历代码的输出如下,想实现按IP地址聚合的指定格式输出,请问该如何实现?

原列表与代码

my_list = [{'xxxxx1': ['123.123.123.1','hey','hello']},{'xxxxx2':['123.123.123.2','hi','HEY']},{'xxxxx3':['123.123.123.3','foo','bar']},{'xxxxx3':['123.123.123.2','foo','bar']}]

for item in my_list:
        for k in item:
            print(item[k])

现有输出

['123.123.123.1', 'hey', 'hello']
['123.123.123.2', 'hi', 'HEY']
['123.123.123.3', 'foo', 'bar']
['123.123.123.2', 'foo', 'bar']

期望输出

123.123.123.1
hey hello
123.123.123.2
hi HEY
foo bar
123.123.123.3
foo bar

实现方法

可以通过字典构建IP地址到对应内容列表的映射,先遍历原列表收集数据,再按IP分组输出:

代码实现

my_list = [{'xxxxx1': ['123.123.123.1','hey','hello']},{'xxxxx2':['123.123.123.2','hi','HEY']},{'xxxxx3':['123.123.123.3','foo','bar']},{'xxxxx3':['123.123.123.2','foo','bar']}]

# 初始化字典,存储IP到对应内容的映射
ip_groups = {}

# 遍历原列表,整理数据
for item in my_list:
    for _, value_list in item.items():
        ip = value_list[0]
        content = ' '.join(value_list[1:])
        # 按IP聚合内容:存在则追加,不存在则新建条目
        if ip in ip_groups:
            ip_groups[ip].append(content)
        else:
            ip_groups[ip] = [content]

# 按分组输出结果
for ip, contents in ip_groups.items():
    print(ip)
    for content in contents:
        print(content)

代码说明

  1. 数据收集:遍历原列表中的每个字典,提取IP地址(列表第一个元素),将后续内容用空格拼接成字符串,存入ip_groups字典,key为IP,value为该IP对应的内容列表。
  2. 分组输出:遍历ip_groups字典,先打印IP地址,再依次输出该IP对应的每一行内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:25:40