Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将带有if条件的for循环从单行中断为多行_Python_If Statement_For Loop_Lambda_Conditional - Fatal编程技术网

Python 将带有if条件的for循环从单行中断为多行

Python 将带有if条件的for循环从单行中断为多行,python,if-statement,for-loop,lambda,conditional,Python,If Statement,For Loop,Lambda,Conditional,我真的对代码的这一部分感到困惑: 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 >

我真的对代码的这一部分感到困惑:

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
现在,我有两个问题:

请解释一下这两行到底是做什么的。 如何在执行相同任务的同时将它们分成多行? 谢谢和问候。

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

线

groupby创建元组列表键、组和我使用字典

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():

你为什么不问问作者?@TigerhawkT3不可用如果这是一本书中的,我相信你会在那里找到答案。你能解释一下“.”的拆分吗,1[0]?“.”、1和[0]在此处的作用是什么?我已经在这个问题中包含了日志文件,这个程序readstry print 192.168.0.1.split'',1和print 192.168.0.1.split'',1[0],您将看到.perfect。但我仍然怀疑furas,我想基于日志文件的最后一次出现进行拆分,如果cnt>100,则提取最后一个字符串。我知道使用rsplit,但它给出的错误是列表没有“split”属性。您有rslit和[-1]更正:rsplit r表示右,因为它是从右向左的
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():