将文本文件中的选定列读入python中的列表

时间:2013-04-03 18:36:39

标签: python

我有一个包含以下内容的文本文件bat.txt:

  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)

我想将Originator和Nexthop列减去标题复制到包含两个子列表的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中的所有列。选择我想要的列的最佳方法是什么?

1 个答案:

答案 0 :(得分: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')