如何从csv文件的两个特定列创建元组列表?

时间:2018-08-12 12:04:45

标签: python list csv tuples multiple-columns

我的csv文件看起来像这样:

{http://www.omg.org/XMI}id,begin,end,Character
18074,15,19,Tony
18120,39,46,Tony
18172,129,134,Clint
18217,175,180,Bucky
18202,245,249,Tony
18307,352,357,Bucky
18376,1297,1302,Steve
18421,1499,1504,Bruce
18489,1546,1553,Natasha
18527,1709,1712,Bucky

我希望能够从第二行开始,从列beginend创建一个元组列表,而忽略标题行。

到目前为止,我可以创建元组列表,但要所有行和列:

import csv
import tkinter
from tkinter import filedialog
root_tk = tkinter.Tk()
root_tk.wm_withdraw()

filename = filedialog.askopenfilename()

with open(filename, 'r') as f:
    data=[tuple(line) for line in csv.reader(f)]

print(data)



root_tk.destroy()
root_tk.mainloop()

当前输出:

[('{http://www.omg.org/XMI}id', 'begin', 'end', 'Character'), ('18646', '518', '520', 'Anakin'), ('18699', '982', '985', 'Jedi'), ('18714', '1018', '1020', 'Anakin'), ('18766', '1057', '1059', 'Anakin'),...

所需的输出:

[(15, 19), (39,46), (129, 134), (175, 180)...]

在忽略第一行并从中创建元组列表的同时,如何将输出限制为这两列?

谢谢!

编辑

我现在可以打印所需的元组,但是仍然无法从输出中删除第一行。

另外,如何将输出从字符串元组转换为整数?

2 个答案:

答案 0 :(得分:5)

您可以使用DictReader并根据需要的列创建元组

import csv

filename = filedialog.askopenfilename()
with open(filename, 'r') as f:
    data=[(int(line['begin']),int(line['end'])) for line in  csv.DictReader(f)]
    print data

输出:

[(15, 19), (39, 46), (129, 134), (175, 180), (245, 249), (352, 357), (1297, 1302), (1499, 1504), (1546, 1553), (1709, 1712)]

希望这有帮助:)

答案 1 :(得分:3)

您可以使用pandas

In [615]: df = pd.read_csv('eg.csv')

In [616]: [(begin, end) for _, begin, end, _ in df.values.tolist()]
Out[616]:
[(15, 19),
 (39, 46),
 (129, 134),
 (175, 180),
 (245, 249),
 (352, 357),
 (1297, 1302),
 (1499, 1504),
 (1546, 1553),
 (1709, 1712)]

如果您想使用csv模块,可以尝试

In [627]: with open('eg.csv', 'r') as f:
     ...:     csv_data = next(csv.reader(f), None)          # Skip first row
     ...:     data=[(int(line[1]), int(line[2])) for line in csv.reader(f) if line]
     ...:

或者根本没有任何导入的模块

In [639]: with open('eg.csv', 'r') as f:
     ...:     f.readline()               # Skip first row
     ...:     data=[tuple(map(int, line.split(',')[1:3])) for line in f.readlines() if line.strip()]
     ...: