[英]Taking a list, comparing values, creating dictionary with several keys
我正在嘗試獲取一個具有IP地址和端口號的列表,並以127.0.0.1:21,80,443
格式打印數據。 這是虛擬數據的示例。
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
我希望如上所述輸出這些數據。 現在,我將數據存儲在列表中,並希望將端口與IP地址相關聯,因此不會在每個端口上重復IP地址。 該數據應輸出到:
127.0.0.1:80,443
192.168.1.1:21
192.168.1.2:22,3389,5900
使用defaultdict,您可以收集每個地址的端口,並像下面這樣一次將它們全部打印出來:
from collections import defaultdict
address_to_ports = defaultdict(list)
with open('file1') as f:
for address in f:
address_to_ports[address.strip()].append(next(f).strip())
print(address_to_ports)
print(['{}:{}'.format(a, ','.join(p)) for a, p in address_to_ports.items()])
defaultdict(<class 'list'>, {'127.0.0.1': ['80', '443'], '192.168.1.1': ['21'], '192.168.1.2': ['22', '3389', '5900']})
['127.0.0.1:80,443', '192.168.1.1:21', '192.168.1.2:22,3389,5900']
您可以使用格式-而不是僅打印列表中的每個元素,請執行以下操作:
print "{0} : {1}".format(list[0], list[1])
不過,您尚未指定輸入是什么。 您應該在下次添加它。
讓我們假設您的列表在名為“ ip_list.txt”的文件中
f = open("ip_list.txt","r")
count = 2
dict_of_ip = {}
ip = ''
for i in f:
if count%2 == 0:
if i.strip() not in dict_of_ip.keys():
ip = i.strip()
dict_of_ip[ip] = []
else:
dict_of_ip[ip].append(i.strip())
count = count + 1
print(dict_of_ip)
輸出:
{'192.168.1.1': ['21'], '127.0.0.1': ['80', '443']}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.