将多个列表写入csv Python [英] Writing multiple lists to csv Python

查看:95
本文介绍了将多个列表写入csv Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个将多个列表写入单个csv文件的函数,并且我能够获取要写入的列标题,但没有任何数据.我的数据在类似于此[92,3801,2,22,4]的列表中,第二个数据为[3.0,2,23,5],我正在寻找有关此方面的指导.谢谢!

Im trying to write a function that writes multiple lists to a singular csv file and i am able to get the column titles to write, but not any of the data. My data is in lists that are similar to this [92,3801,2,22,4] and the second is [3.0,2,23,5] and im looking for guidance on this. Thank you!

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.

As the name implies, writerows writes rows, not columns. Furthermore, your lists are not equally sized, so you'll need to do something to account for that. The standard way of handling such a thing is using 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])

这篇关于将多个列表写入csv Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆