将 Python 列表写入 csv 中的列 [英] Writing Python lists to columns in csv

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

问题描述

我有 5 个列表,长度都相同,我想将它们以 CSV 格式写入 5 列.到目前为止,我只能用这个代码向一列写一个:

I have 5 lists, all of the same length, and I'd like to write them to 5 columns in a CSV. So far, I can only write one to a column with this code:

with open('test.csv', 'wb') as f:
    writer = csv.writer(f)
    for val in test_list:
        writer.writerow([val])

如果我添加另一个 for 循环,它只会将该列表写入同一列.有人知道获得五个单独列的好方法吗?

If I add another for loop, it just writes that list to the same column. Anyone know a good way to get five separate columns?

推荐答案

将它们更改为行:

rows = zip(list1, list2, list3, list4, list5)

然后:

import csv

with open(newfilePath, "w") as f:
    writer = csv.writer(f)
    for row in rows:
        writer.writerow(row)

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

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