2017-10-22 313 views
1

我試圖編寫一個函數,寫入多個列表到一個單一的csv文件,我能夠獲得列標題寫入,但沒有任何數據。我的數據列表類似於[92,3801,2,22,4],第二個是[3.0,2,23,5],我正在尋找這方面的指導。謝謝!向csv寫入多個列表Python

import csv 
def export_results(number_of_words_sentence,mean_word_per_sentence): 
    with open("assignment_7_results.csv", "w", newline="") as Assignment_7_results: 
     writer = csv.writer(Assignment_7_results) 
     writer.writerow(["Number of Words", "Words/Sentence"]) 
    # Our .csv file will have two columns, one for the dict keys and one for the dict values 
     writer.writerows(number_of_words_sentence) 
     writer.writerows(mean_words_per_sentence) 
+1

顧名思義,''編寫者'寫_rows_,而不是列。您必須依次壓縮並逐個遍歷每對元素,並調用'authorow' –

回答

1

顧名思義,writerows寫入行,而不是列。此外,你的名單並不相同,所以你需要做一些事情來解決這個問題。處理這種事的標準方法是使用itertools.zip_longest

from itertools import zip_longest # izip_longest in python2.x 

with open("assignment_7_results.csv", "w") as f: 
    w = csv.writer(f) 
    w.writerow(["Number of Words", "Words/Sentence"]) 
    for x, y in zip_longest(number_of_words_sentence, mean_word_per_sentence): 
     w.writerow([x, y]) 
+0

我試圖將其添加到我的代碼中,並且它沒有生成輸出 –

+0

@ J.McCraiton好吧。和?你認爲這條信息可以幫助我瞭解什麼是錯的? –

+0

目前它生成標題並且在其下面沒有列。對不起,應該是更具描述性。我的壞人。 –