2017-09-05 45 views
1

我有這樣的代碼:打印的特定字段在Python 3開放

with open('/home/adiel/log', 'r') as list: 
    content = list.read() 
    rows = content.split("\n") 
    for row in rows: 
     infos = row.split(' ') 
     print(infos) 

返回我的這些值:

['2', '064328796150', 'eni-4bad5a20', '172.18.0.124', '172.18.0.5', '3306', '39064', '6', '14', '4123', '1504618064', '1504618121', 'ACCEPT', 'OK'] 
['2', '064328796150', 'eni-4bad5a20', '172.18.0.124', '172.18.0.5', '3306', '62717', '6', '16', '5981', '1504618064', '1504618121', 'ACCEPT', 'OK'] 
['2', '064328796150', 'eni-4bad5a20', '172.18.0.5', '172.18.0.124', '52909', '3306', '6', '37', '7112', '1504618064', '1504618121', 'ACCEPT', 'OK'] 

我想只有從場1和4的值,例如。我怎樣才能做到這一點?

+0

請注意,你可能不想說「的名單」,因爲「名單」是內置在Python(https://開頭的文檔.python.org/2/library/functions.html#func-list)並且這個破壞它。 「作爲list_file」可能會更清晰。 – dmcc

回答

0

你可以使用列表理解來做到這一點如下:

with open('/home/adiel/log', 'r') as f: 
    print([[x.split()[0], x.split()[3]] for x in f]) 

,或者如果你想打印分開的每一行:

with open('/home/adiel/log', 'r') as f: 
    for line in [[x.split()[0], x.split()[3]] for x in f]: 
     print(line) 
+0

好的,這個例子工作正常!謝謝,還有其他人。 – Adiel

+0

很高興幫助:-) –

+0

只是對此代碼的另一個疑問,我現在沒有,如果我把它放在這裏將是最好的方式,所以我打開另一個主題:https://stackoverflow.com/questions/46064932/compare -ax-splitfield-with-some-values?noredirect = 1#comment79090665_46064932 – Adiel

2

由於蟒蛇是0索引:

row = row.split(' ') 
infos = row[0], row[3] 

但你也可能不得不在infos存儲到列表訪問後

1

itemgetter可以提供一個優雅的解決方案:

from operator import itemgetter 
ig = itemgetter(0,3) 

with open('/home/adiel/log', 'r') as list: 
    content = list.read() 
    rows = content.split("\n") 
    for row in rows: 
     infos = row.split(' ') 
     relevant_infos=ig(infos) 
     print(relevant_infos) 
+0

好主意,除非你沒有正確地使用itemgetter – JBernardo

+0

@Jernernardo謹慎地詳細說明這裏究竟是什麼錯誤? – Mureinik

+0

你有沒有試過這個代碼?提示:ig(0,3),應該是ig(the_list) – JBernardo