gpt4 book ai didi

python - 如何计算二维列表或字典列表?

转载 作者:太空宇宙 更新时间:2023-11-04 02:52:10 26 4
gpt4 key购买 nike

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

这是我迄今为止尝试过的。

字典列表:

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

或二维列表

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

我想将 192.168, UDP 移动到另一个包含计数的列表,因为它出现了 x 次以上。我试过 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} 到另一个列表。

最佳答案

如果您的数据是第二种形式的二维列表,您可以使用:

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

关于python - 如何计算二维列表或字典列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43554500/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com