简体   繁体   中英

Read a csv file using list comprehension

I read a csv file this way:

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']) 

Now I'm trying this

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

But as I'm returning record instead of record['link'] I got a dict, how can I get the same result as in the first case using list comprehension?

您正在附加record['link'] ,所以这就是您应该在理解中包含的内容:

links = [record['link'] for record in reader if record['link']]

只需使用与调用links.append()相同的表达式,即record['link']

links = [record['link'] for record in reader if record['link']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM