使用list comprehension读取csv文件

时间:2016-04-03 10:19:41

标签: python csv list-comprehension

我这样读了一个csv文件:

links = []
with open(join(input_path,'data.csv')) as csvfile:
    reader = csv.DictReader(csvfile)
    for record in (reader):
        if record['link']:
            links.append(record['link']) 

现在我正在尝试这个

with open(join(input_path,'data.csv')) as csvfile:
    reader = csv.DictReader(csvfile)
    a = [record for record in reader if record['link']]

但是当我回复record而不是record['link']时,我得到了一个词典,我怎样才能得到与使用列表推导的第一种情况相同的结果?

2 个答案:

答案 0 :(得分:1)

只需使用与promise4()调用相同的表达式,即links.append()

record['link']

答案 1 :(得分:1)

您正在追加links = [record['link'] for record in reader if record['link']] ,以便了解您应该包含在理解中的内容:

record['link']