0

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
4

2 に答える 2

0

subnet_dict の文字列の末尾が常に '/32' になることがわからない場合は、次のようにします。

for row in datafile:
    dstip = row[2]
    if dstip in [str.split('/')[0] for str in subnet_dict.keys()]:
        for k in subnet_dict:
            if k.split('/')[0] == dstip:
                print dstip + ' ' + subnet_dict[k] + ' was FOUND in the dictionary'
    else:
        print dstip + ' was not found'

もしそうなら、これで十分です:

for row in datafile:
    dstip = row[2]
    if dstip + '/32' in subnet_dict:
        print dstip + ' ' + subnet_dict[dstip + '/32'] + ' was FOUND in the dictionary'
    else:
        print dstip + ' was not found'
于 2015-09-11T00:25:16.823 に答える