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