2017-04-22 9 views
2

テキストファイルから情報を取得しています。パケットのIPアドレスとタイプ。私はIP/Typeの各出現をリスト/辞書に入れていますか?カウントを探して、IP /タイプがx回発生する場合は、その情報を別のリストに移動したいと考えています。2Dリストまたはディクショナリのリストを数えるには?

これはこれまで私が試したことです。

Dictsの一覧:

data = [{'ip': '192.168', 'type': 'UDP'}, 
     {'ip': '192.173', 'type': 'TCP'}, 
     {'ip': '192.168', 'type': 'UDP'}] 

または2次元の一覧

data = [['192.168', 'UDP'], 
     ['192.173', 'TCP'], 
     ['192.168', 'UDP']] 

私はそれがx倍以上に現れたため、カウントを持つ別のリストに192.168、UDPを移動したいです。私はCounterを試しましたが、私はそれを得ることができますが、IPとタイプではなく、IPを渡す。

ipInfo = Counter(k['ip'] for k in data if k.get('ip')) 
for info, count in ipInfo.most_common(): 
    print info, count 

これは192.168, 2ない192.168, UDP, 2を出力します。

私の例では、別のリストに[192.168, UDP, 2]または{'ip': '192.168', 'type': 'UDP', 'count':2}を追加したいと考えています。

+0

あなたはカウンター(data.iteritemsでkのK [ 'IP']()k.get( 'IP')の場合)またはカウンタ(data.iteritems())のような意味でください。どちらもうまくいかないようです。 –

答えて

0

あなたのデータはあなたの第二の形式での2Dリストである場合は、あなたが使用することができます。

In [1]: data = [['192.168', 'UDP'], 
    ...:   ['192.173', 'TCP'], 
    ...:   ['192.168', 'UDP']] 

In [2]: c = Counter(tuple(r) for r in data) 

In [3]: for info, count in c.most_common(): 
    ...:  print info, count 

(u'192.168', u'UDP') 2 
(u'192.173', u'TCP') 1 
+0

これは完璧です。どうもありがとう。私はPythonにはまだまだ新しいので、これらのデータ構造に慣れていなくて、最近辞書について学んだだけです。 –

0

ここでの-リストリストおよびリストの-dictsの両方のために働くだろう何か:

from collections import Counter, Sequence 
from pprint import pprint 

def move_info(data): 
    """ Copy info from data list into another list with an occurence count added. 
     data can be a list of dicts or tuples. 
    """ 
    if isinstance(data[0], dict): 
     counter = Counter((dct['ip'], dct['type']) for dct in data1) 
     result = [dict(ip=info[0], type=info[1], count=count) 
          for info, count in sorted(counter.items())] 
     return result 
    elif isinstance(data[0], Sequence): 
     counter = Counter(tuple(elem) for elem in data2) 
     result = [list(info) + [count] for info, count in sorted(counter.items())] 
     return result 
    raise TypeError("Can't move info from a {}".format(type(data))) 

# list of dicts 
data1 = [{'ip': '192.168', 'type': 'UDP'}, 
     {'ip': '192.173', 'type': 'TCP'}, 
     {'ip': '192.168', 'type': 'UDP'}] 

# list of lists 
data2 = [['192.168', 'UDP'], 
     ['192.173', 'TCP'], 
     ['192.168', 'UDP']] 

another_list = move_info(data1) 
pprint(another_list) 
print('') 
another_list = move_info(data2) 
pprint(another_list) 

出力:

[{'count': 2, 'ip': '192.168', 'type': 'UDP'}, 
{'count': 1, 'ip': '192.173', 'type': 'TCP'}] 

[['192.168', 'UDP', 2], ['192.173', 'TCP', 1]] 
0
packetDict = {} 

data = [['192.168', 'UDP'], 
     ['192.173', 'TCP'], 
     ['192.168', 'UDP']] 

for packetInfo in data: 
    packetInfo = tuple(packetInfo) 

    if packetInfo not in packetDict: 
    packetDict[packetInfo] = 1 
    else: 
    packetDict[packetInfo] += 1 

for pkt,count in packetDict.items(): 
    print(pkt,count) 

RESSULTは

('192.168', 'UDP') 2 
('192.173', 'TCP') 1 
関連する問題