如何计算2D列表或词典列表?

时间:2017-04-22 02:15:49

标签: python list dictionary 2d

我从文本文件,IP地址和数据包类型中获取信息。我将每次出现的IP / Type放入列表/字典中?然后我想找到计数,如果IP /类型出现x次,那么我想将该信息移动到另一个列表。

这是我到目前为止所尝试过的。

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']] 

我想将192.168,UDP移动到另一个带有计数的列表,因为它显示的次数超过x次。我尝试了Counter,但我只能通过ip而不是ip和type。

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}添加到其他列表中。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

这里的内容适用于列表列表和列表列表:

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]]

答案 2 :(得分: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