2016-09-22 54 views
0

我需要从.csv文件创建元组列表。csv文件到元组列表 - 排除某些列

import csv 
with open('movieCatalogue.csv') as f: 
    data=[tuple(line) for line in csv.reader(f)] 
    data.pop(0) 

print(data) 

这是除了在.csv文件的第一列近乎完美的包含产品ID,我不会在一个元组:在另一篇文章中的成员使用此代码建议。有没有办法阻止每行中的某些列被复制。

回答

0

首先,我想你会丢掉标题行data.pop(0)。你可以在阅读时跳过一个列表dealloc/move。

然后,当您撰写你的元组,使用子列表语法刚落,第一个元素:line[start:stop:step],从索引0

import csv 
with open('movieCatalogue.csv') as f: 
    cr = csv.reader(f) 
    # drop the first line: better as next(f) 
    # since it works even if the title line is multi-line! 
    next(cr) 

    data=[tuple(line[1:]) for line in cr] # drop first column of each line 

print(data)