2013-04-03 58 views
0

我有一個包含一個文本文件bat.txt如下:選定列到名單在python

Originator  (#/255)   Nexthop [outgoingIF]: Potential nexthops ... [B.A.T.M.A.N. adv 0.2-beta r1457, MainIF/MAC: eth0/fe:fe:00:00:01:01] 
fe:fe:00:00:05:01 (223) fe:fe:00:00:02:01 [  eth0]: fe:fe:00:00:03:01 (96) fe:fe:00:00:02:01 (223) 
fe:fe:00:00:04:01 (233) fe:fe:00:00:02:01 [  eth0]: fe:fe:00:00:03:01 (100) fe:fe:00:00:02:01 (233) 
fe:fe:00:00:02:01 (254) fe:fe:00:00:02:01 [  eth0]: fe:fe:00:00:02:01 (254) fe:fe:00:00:03:01 (100) 
fe:fe:00:00:07:01 (203) fe:fe:00:00:02:01 [  eth0]: fe:fe:00:00:02:01 (203) fe:fe:00:00:03:01 (88) 
fe:fe:00:00:08:01 (196) fe:fe:00:00:02:01 [  eth0]: fe:fe:00:00:03:01 ( 0) fe:fe:00:00:02:01 (196) 
fe:fe:00:00:03:01 (244) fe:fe:00:00:02:01 [  eth0]: fe:fe:00:00:03:01 (104) fe:fe:00:00:02:01 (244) 
fe:fe:00:00:09:01 (184) fe:fe:00:00:02:01 [  eth0]: fe:fe:00:00:02:01 (184) fe:fe:00:00:03:01 (72) 
fe:fe:00:00:06:01 (214) fe:fe:00:00:02:01 [  eth0]: fe:fe:00:00:03:01 (76) fe:fe:00:00:02:01 (214) 

我想給發起人和下一跳列減去標題複製到Python列表包含兩個子列表,例如somelist = [[],[]]

with open('bat.txt', 'r') as file: 
...  file.readline() # to skip the first line 
...  rows = [[int(x) for x in line.split()[:-1]] for line in file] 
...  cols = [list(col) for col in zip(*rows)] 

這應該讀取列表col中的所有列。什麼是僅選擇我想要的列的最佳方式?

回答

3

這是你在追求什麼?

#!/usr/bin/env python 

orig=[] 
nex=[] 

with open("bat.txt") as fd: 
    fd.readline() 
    for line in fd: 
     orig.append(line.split()[0]) 
     nex.append(line.split()[2]) 

col=[i for i in zip(orig, nex)] 

內容的col

('fe:fe:00:00:05:01', 'fe:fe:00:00:02:01') 
('fe:fe:00:00:04:01', 'fe:fe:00:00:02:01') 
('fe:fe:00:00:02:01', 'fe:fe:00:00:02:01') 
('fe:fe:00:00:07:01', 'fe:fe:00:00:02:01') 
('fe:fe:00:00:08:01', 'fe:fe:00:00:02:01') 
('fe:fe:00:00:03:01', 'fe:fe:00:00:02:01') 
('fe:fe:00:00:09:01', 'fe:fe:00:00:02:01') 
('fe:fe:00:00:06:01', 'fe:fe:00:00:02:01') 
+1

是。真是太棒了,謝謝。 – 2013-04-03 18:55:21