2017-01-02 21 views
-4

我真的與這部分代碼混淆:打破for循環使用,如果從單一的線路條件爲多行

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. 如何將它們分成多行,同時承擔相同的任務?

感謝和問候。

+1

你爲什麼不問作者? – TigerhawkT3

+0

@ TigerhawkT3不可用 –

+0

如果這是來自一本書,我相信那裏你會找到答案。 – MichaelMMeskhi

回答

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

你能解釋一下split('。',1)[0]嗎? ''的作用是什麼? ,1和[0]在這裏? 我已經在這個程序讀取的問題中包含日誌文件 –

+0

嘗試'print(「192.168.0.1」.split('。',1))''和print(「192.168.0.1」.split('。' ,1)[0])',你會看到。 – furas

+0

完美。但仍然懷疑furas,我想根據最後一次出現的日誌文件進行拆分,並提取最後一個字符串(如果cnt> 100)。我知道使用rsplit(),但它給出的錯誤列表沒有'split'屬性。 –