【问题标题】:Filter one column and count the occurence in the other column过滤一列并计算另一列中的出现次数
【发布时间】:2019-02-25 08:13:54
【问题描述】:

我正在尝试使用第四列(警报)在第二列(源 IP)中获得最高出现次数。

示例列表:

test=[["2019-01-05 03:15:49","192.168.0.15","192.168.0.116:4070","network discover"],
["2019-01-05 03:25:49,"192.168.0.15","192.168.0.1:4070","network discover"],
["2019-01-05 03:35:49","192.168.0.15","192.168.0.116:4070","network discover"],
["2019-01-05 03:55:49,"192.168.0.12","192.168.0.1:4070","network discover"],
["2019-01-05 04:38:13","192.168.0.15","192.168.0.41:445","ETERNALBLUE tool"],
["2019-01-05 05:28:13","192.168.0.12","192.168.0.39:445","ETERNALBLUE tool"]]

期望的输出

网络发现,192.168.0.15 = 3

网络发现,192.168.0.12 = 1

永恒之蓝工具,192.168.0.15 = 1

永恒之蓝工具,192.168.0.12 = 1

【问题讨论】:

  • 嘿 :) 你的问题是什么?您在实现所需输出的过程中遇到了哪些困难?

标签: python for-loop lambda counter


【解决方案1】:

使用collections.defaultdict

例如:

from collections import defaultdict

test=[["2019-01-05 03:15:49","192.168.0.15","192.168.0.116:4070","network discover"],
["2019-01-05 03:25:49","192.168.0.15","192.168.0.1:4070","network discover"],
["2019-01-05 03:35:49","192.168.0.15","192.168.0.116:4070","network discover"],
["2019-01-05 03:55:49","192.168.0.12","192.168.0.1:4070","network discover"],
["2019-01-05 04:38:13","192.168.0.15","192.168.0.41:445","ETERNALBLUE tool"],
["2019-01-05 05:28:13","192.168.0.12","192.168.0.39:445","ETERNALBLUE tool"]]

result = defaultdict(int)
for i in test:
    result[(i[-1], i[1])] += 1
print(result)

输出:

defaultdict(<type 'int'>, {
    ('network discover', '192.168.0.12'): 1, 
    ('ETERNALBLUE tool', '192.168.0.15'): 1, 
    ('ETERNALBLUE tool', '192.168.0.12'): 1, 
    ('network discover', '192.168.0.15'): 3
    })

【讨论】:

    【解决方案2】:

    你可以使用Counter:

    from collections import Counter
    from pprint import pprint
    
    c = Counter((i[-1], i[1]) for i in test)
    
    pprint(c)
    

    输出:

    Counter({('network discover', '192.168.0.15'): 3,
             ('network discover', '192.168.0.12'): 1,
             ('ETERNALBLUE tool', '192.168.0.15'): 1,
             ('ETERNALBLUE tool', '192.168.0.12'): 1})
    

    【讨论】:

      猜你喜欢
      • 2019-03-27
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 2022-06-16
      相关资源
      最近更新 更多