2013-04-14 42 views
0

我有两个列表:写多个列表以CSV

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

我想写名单xy到CSV文件,使之在列写着:

西1:
一个
b
ç

西2:
Ĵ
ķ

西3:
d
Ë
˚F

山口4:

Ñ
ö

等我真的不是真的重新如何做到这一点。

回答

0

您可以使用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) 

如果你有不同的长度,那么你不妨看看itertools.izip_longest并指定合适的fillvalue=代替使用内建zip

+1

不需要'list(...)'构造函数 – jamylak