在Python的列中将不同大小的列表写入csv [英] Write lists of different size to csv in columns in Python

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

问题描述

我需要在列中将所有长度都不同的列表写到CSV文件中.

I need to write lists that all differ in length to a CSV file in columns.

我目前有:

d=lists
writer = csv.writer(fl)
for values in zip(*d):
    writer.writerow(values)

仅部分起作用.我怀疑正在发生的事情是,它停止了压缩,直到列表的长度最短为止.

which works only partially. What I suspect is happening is that it stops zipping up until the lists with the list of the shortest length.

推荐答案

下面的代码适用于Python3.如果使用Python 2,请导入izip_longest而不是zip_longest.

Code below is for Python 3. If you use Python 2, import izip_longest instead of zip_longest.

import csv
from itertools import zip_longest

d = [[2,3,4,8],[5,6]]

with open("file.csv","w+") as f:
    writer = csv.writer(f)
    for values in zip_longest(*d):
        writer.writerow(values)

结果:

2,5
3,6
4,
8,

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

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