CSV的2D列表-按列 [英] 2D list to csv - by column
本文介绍了CSV的2D列表-按列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将2D列表的内容导出到csv文件中.
I'd like to export the content of a 2D-list into a csv file.
子列表的大小可以不同.例如,二维列表可以是:
The size of the sublists can be different. For example, the 2D-list can be something like :
a = [['a','b','c','d'],['e','f'],['g'],[],['h','i']]
a = [ ['a','b','c','d'], ['e','f'], ['g'], [], ['h','i'] ]
我希望我的csv像这样存储数据-按列":
I want my csv to store the data like this - "by column" :
a,e,g, ,h
b,f, , ,i
c
d
我是否必须添加一些空格以使每个子列表具有相同的大小?还是有其他方法可以做到这一点?
Do I have to add some blank spaces to get the same size for each sublist ? Or is there another way to do so ?
谢谢您的帮助
推荐答案
您可以使用 itertools.zip_longest
:
import itertools, csv
a = [ ['a','b','c','d'], ['e','f'], ['g'], [], ['h','i'] ]
with open('filename.csv', 'w') as f:
write = csv.writer(f)
write.writerows(list(itertools.zip_longest(*a, fillvalue='')))
输出:
a,e,g,,h
b,f,,,i
c,,,,
d,,,,
这篇关于CSV的2D列表-按列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文