向csv写入多个列表Python
我试图编写一个函数,写入多个列表到一个单一的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)
顾名思义,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])
我试图将其添加到我的代码中,并且它没有生成输出 –
@ J.McCraiton好吧。和?你认为这条信息可以帮助我了解什么是错的? –
目前它生成标题并且在其下面没有列。对不起,应该是更具描述性。我的坏人。 –
顾名思义,''编写者'写_rows_,而不是列。您必须依次压缩并逐个遍历每对元素,并调用'authorow' –