2016-04-03 55 views
-1

閱讀csv文件我看了一個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']我一個字典,我怎樣才能得到與使用列表理解的第一種情況相同的結果?

回答

1

要追加record['link'],所以這是你應該包括在理解什麼:

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

只需使用相同的表達式在調用links.append(),即record['link']

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