Write lists of different size to csv in columns in

2020-04-28 09:36发布

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

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.

标签: python list csv
2条回答
劳资没心,怎么记你
2楼-- · 2020-04-28 10:12

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)

Result:

2,5
3,6
4,
8,
查看更多
地球回转人心会变
3楼-- · 2020-04-28 10:24

There's no 'neat' way to write it since, as you said, zip truncates to the length of the shortest iterable.

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):

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.

EDIT: corrected example

查看更多
登录 后发表回答