将带有 if 条件的 for 循环从单行拆分为多行

Break a for loop with if condition from single line into multiple lines

我对这部分代码真的很困惑:

newip = []
c = Counter()
for key, group in groupby(logfile, key=lambda e: e.split('.',1)[0]):
   for entry in group:
      c.update(re.findall(r'[0-9]+(?:\.[0-9]+){3}', entry))
   newip.extend(ip for ip, cnt in c.items() if cnt > 10)

如何在执行相同任务时将这两行分成多行?

for key, group in groupby(logfile, key=lambda e: e.split('.',1)[0]):
...
   newip.extend(ip for ip, cnt in c.items() if cnt > 10)

日志文件:

12/30-04:09:41.070967 [**] [1:10000001:1] snort alert [1:0000001] [**] [classification ID: 0] [Priority ID: 0] {ICMP} 192.168.232.2:41676 -> 192.168.248.2:21
12/30-04:09:41.070967 [**] [1:10000001:1] snort alert [1:0000001] [**] [classification ID: 0] [Priority ID: 0] {ICMP} 192.168.232.2:41673 -> 192.168.248.2:21

现在,我有两个问题:

  1. 请解释这两行到底做了什么。
  2. 如何将它们分成多行,同时执行相同的任务?

感谢和问候。

newip.extend(ip for ip, cnt in c.items() if cnt > 10)

for ip, cnt in c.items() 
    if cnt > 10:
       #newip.extend( [ip] ) # with [ ]
       newip.append( ip ) # without [ ]

for key, group in groupby(logfile, key=lambda e: e.split('.',1)[0]):

会(但可能 groupby 创建元组列表 (key, group) 并且我使用字典)

groups = groupby(logfile, key=lambda e: e.split('.',1)[0])

for key, group in groups.items():

这是我猜的

groups = dict()

for element in logfile:
    key = element.split('.',1)[0]
    if key not in groups:
       groups[key] = []
    groups[key].append(element)

for key, group in groups.items():