[英]Taking a list, comparing values, creating dictionary with several keys
I am trying to take a list that has IP address and port numbers and print the data out to be in this format 127.0.0.1:21,80,443
. 我正在尝试获取一个具有IP地址和端口号的列表,并以127.0.0.1:21,80,443
格式打印数据。 Here is a sample of dummy 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
I would like this data to output as stated above. 我希望如上所述输出这些数据。 Right now, I have the data in a list and am looking to associate the ports with the IP addresses so it is not repeating the IP address to each port. 现在,我将数据存储在列表中,并希望将端口与IP地址相关联,因此不会在每个端口上重复IP地址。 This data should output to: 该数据应输出到:
127.0.0.1:80,443
192.168.1.1:21
192.168.1.2:22,3389,5900
Using a defaultdict you can collect the ports for each address, and the print them out all at once like: 使用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']
You can use format - instead of just printing every element of the list do the following: 您可以使用格式-而不是仅打印列表中的每个元素,请执行以下操作:
print "{0} : {1}".format(list[0], list[1])
You haven't specified what the input is, though. 不过,您尚未指定输入是什么。 You should add it next time. 您应该在下次添加它。
Let us suppose your list is in a file called 'ip_list.txt' The code 让我们假设您的列表在名为“ 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)
Output: 输出:
{'192.168.1.1': ['21'], '127.0.0.1': ['80', '443']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.