简体   繁体   English

在Python的列中将不同大小的列表写入csv

[英]Write lists of different size to csv in columns in Python

I need to write lists that all differ in length to a CSV file in columns. 我需要在列中编写一个长度与CSV文件不同的列表。

I currently have: 我目前有:

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. 我怀疑正在发生的事情是,它停止了压缩,直到列表的长度最短为止。

Code below is for Python 3. If you use Python 2, import izip_longest instead of zip_longest. 下面的代码适用于Python3。如果使用Python 2,请导入izip_longest而不是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)

Result: 结果:

2,5
3,6
4,
8,

There's no 'neat' way to write it since, as you said, zip truncates to the length of the shortest iterable. 正如您所说的那样,没有“整洁”的方式来编写它,因为zip会截断到最短可迭代的长度。

Probably the simplest way would be to just pad with None or empty strings (Not sure offhand what the behavior of writerow is with None values): 可能最简单的方法是只填充None或空字符串(不确定使用None值立即写行的行为):

maxlen = max([len(member) for member in d])
[member.extend([""] * (maxlen - len(member))) for member in d]
for values in zip(*d):
    ...

Alternatively, you could just construct each row inside the for loop instead of using zip , which would be more efficient but a lot wordier. 或者,您可以只在for循环中构造每一行,而不是使用zip ,这会更高效,但要复杂得多。

EDIT: corrected example 编辑:更正的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM