简体   繁体   English

将多个列表写入CSV

[英]Write multiple lists to CSV

I have two lists: 我有两个清单:

x = [['a','b','c'], ['d','e','f'], ['g','h','i']]
y = [['j','k','l'], ['m','n','o'], ['p','q','r']]

I'd like to write lists x and y to a CSV file such that it reads in columns: 我想将列表xy写入CSV文件,以便它读取列:

Col 1: 第1栏:
a 一种
b b
c C

Col 2: 第2列:
j Ĵ
k ķ
l

Col 3: 第3列:
d d
e Ë
f F

Col 4: 第4列:
m
n ñ
o Ø

etc. I'm not really sure how to do this. 等等。我不太确定该怎么做。

You can use zip to do the transpose and csv to create your output file, eg: 您可以使用zip进行转置,并使用csv创建输出文件,例如:

x = [['a','b','c'], ['d','e','f'], ['g','h','i']]
y = [['j','k','l'], ['m','n','o'], ['p','q','r']]

from itertools import chain
import csv
res = zip(*list(chain.from_iterable(zip(x, y))))
with open(r'yourfile.csv', 'wb') as fout:
    csvout = csv.writer(fout)
    csvout.writerows(res)

If you have unequal lengths, then you may wish to look at itertools.izip_longest and specify a suitable fillvalue= instead of using the builtin zip 如果长度不相等,则不妨查看itertools.izip_longest并指定合适的fillvalue=而不要使用内置的zip

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

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