如何通过列表值对比创建字典,实现IP与多端口关联输出?
嘿,这个需求很常见,用字典来做分组处理就很合适。我给你写个Python的实现方案,清晰易懂还能处理重复端口的情况:
实现思路
核心就是用字典做分组:
- 把输入的字符串按空格拆分,两两配对成「IP-端口」的组合
- 用IP作为字典的键,对应的端口存入集合(自动去重)
- 最后把字典的键值对转换成「IP:端口1,端口2,...」的格式,再拼接成最终输出
代码实现
# 示例输入数据 input_data = "127.0.0.1 80 127.0.0.1 443 192.168.1.1 21 192.168.1.2 22 192.168.1.2 3389 192.168.1.2 5900" # 1. 拆分输入为单个元素列表 items = input_data.split() # 2. 用字典分组IP和端口,集合自动去重端口 ip_port_map = {} for idx in range(0, len(items), 2): current_ip = items[idx] current_port = items[idx + 1] if current_ip not in ip_port_map: ip_port_map[current_ip] = set() ip_port_map[current_ip].add(current_port) # 3. 转换为要求的输出格式 output_parts = [] for ip, ports in ip_port_map.items(): # 可选:排序端口让输出更整齐,不需要可以去掉sorted() port_list = ",".join(sorted(ports)) output_parts.append(f"{ip}:{port_list}") # 拼接成最终结果 final_output = " ".join(output_parts) print(final_output)
输出结果
运行后会得到:
127.0.0.1:80,443 192.168.1.1:21 192.168.1.2:22,3389,5900
如果你的输入里有同一个IP的重复端口,比如127.0.0.1 80 127.0.0.1 80,这段代码也会自动去重,输出127.0.0.1:80,非常实用。
内容的提问来源于stack exchange,提问作者Chelsea
相关产品推荐
相关产品推荐

