2 回答

TA貢獻1796條經驗 獲得超10個贊
你最好使用dict來處理數據:1)IP可以是Dict中的key 2)List可以是Dict中的值。
如果需要,我可以為您創(chuàng)建示例代碼。

TA貢獻1779條經驗 獲得超6個贊
這將操作您的數據,并打印您想要的輸出。我已經嘗試在下面的評論中盡可能地解釋它,但請?zhí)岢鋈魏尾磺宄膯栴}。
from collections import defaultdict
import socket
# build a dictionary of ip -> set of ports
# default dict is cool becasue if the key doesn't exist when accessed,
# it will create it with a default value (in this case a set)
# I'm using a set because I don't want to add the same port twice
ip_to_ports = defaultdict(set)
with open('mres.txt') as fp:
for line in fp:
# grab only the lines we're interested in
if line.startswith('Host:'):
parts = line.strip().split()
ip = parts[1]
port = parts[-1]
# split it by '/' and grab the first element
port = port.split('/')[0]
# add ip and ports to our defaultdict
# if the ip isn't in the defaultdict, it will be created with
# an empty set, that we can add the port to.
# if we run into the same port twice,
# the second entry will be ignored.
ip_to_ports[ip].add(port)
# sort the keys in ip_to_ports by increasing address
for ip in sorted(ip_to_ports, key=socket.inet_aton):
# sort the ports too
ports = sorted(ip_to_ports[ip])
# create a string and print
ports = ', '.join(ports)
print(ip, ports)
添加回答
舉報