繁体   English   中英

清单,比较值,用几个键创建字典

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM