【问题标题】:Break a for loop with if condition from single line into multiple lines将带有 if 条件的 for 循环从单行拆分为多行
【发布时间】:2017-05-16 07:43:16
【问题描述】:

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

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. 如何在执行相同任务的同时将它们分成多行?

感谢和问候。

【问题讨论】:

  • 为什么不问问作者?
  • @TigerhawkT3 不可用
  • 如果这是一本书,我相信你会在那里找到答案。

标签: python if-statement for-loop lambda conditional


【解决方案1】:

线

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

【讨论】:

  • 你能解释一下 split('.',1)[0] 吗? '.' 的作用是什么? , 1 和 [0] 在这里?我已将日志文件包含在该程序读取的问题中
  • 试试print( "192.168.0.1".split('.', 1) ) 和print( "192.168.0.1".split('.', 1)[0] ) 你会看到的。
  • 完美。但我仍然怀疑furas,如果cnt> 100,我想根据最后一次出现的日志文件进行拆分并提取最后一个字符串。我知道使用 rsplit() 但它给出的错误是列表没有'split'属性。
  • 你有rslit()和[-1]
  • 更正:rsplit()(r 表示right,因为它是从右到左)
猜你喜欢
  • 2015-08-24
  • 1970-01-01
  • 2019-02-23
  • 1970-01-01
  • 2023-03-15
  • 2022-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多