我正在尝试遍历 IP 地址列表并检查每个 IP 地址是否作为字典键存在。我的 for 循环为在字典中找到的 IP 地址返回所需的结果,但是对于未找到的 IP 地址,循环多次返回 IP 地址。关于更好的方法来做到这一点的任何想法。
subnet_dict = {'10.6.150.2/32': 'site-A', '10.2.150.2/32': 'site-B', '10.1.2.2/32': 'site-C'}
datafile = [['27/08/2015 18:23', '10/09/2015 12:20', '10.1.2.2', '15356903000'], ['3/09/2015 8:54', '3/09/2015 20:03', '10.1.2.3', '618609571'],
['27/08/2015 22:23', '10/09/2015 10:25', '10.1.2.4', '6067520'], ['27/08/2015 20:14', '10/09/2015 1:35', '10.99.88.6', '4044954']]
for row in datafile:
dstip = row[2]
for key, value in subnet_dict.iteritems():
if dstip in key:
print dstip, value + ' was FOUND in the dictionary'
else:
print dstip + ' was not found'
输出:
10.1.2.2 was not found
10.1.2.2 was not found
10.1.2.2 site-C was FOUND in the dictionary
10.1.2.3 was not found
10.1.2.3 was not found
10.1.2.3 was not found
10.1.2.4 was not found
10.1.2.4 was not found
10.1.2.4 was not found
10.99.88.6 was not found
10.99.88.6 was not found
10.99.88.6 was not found
期望的输出:
10.1.2.2 site-C was FOUND in the dictionary
10.1.2.3 was not found
10.1.2.4 was not found
10.99.88.6 was not found