简体   繁体   English

Python,如何将不等长的嵌套列表写入csv文件?

[英]Python, how to write nested list with unequal lengths to a csv file?

suppose I have an numpy array with structure like this: 假设我有一个结构如下的numpy数组:

[['a','b','c'],[1,2,3],['i','j','k','l'],[5,10,15,20]]

and I want to save it to a csv file that looks like this 我想将它保存到一个看起来像这样的csv文件

a, 1, i, 5
b, 2, j, 10
c, 3, k, 15
,  ,  l, 20

the columns with shorter length just fill with blank. 长度较短的列只需填空。 How can I do that? 我怎样才能做到这一点?

Use itertools.izip_longest : 使用itertools.izip_longest

>>> from itertools import izip_longest
>>> lis =  [['a','b','c'],[1,2,3],['i','j','k','l'],[5,10,15,20]]
>>> list(izip_longest(*lis, fillvalue=''))
[('a', 1, 'i', 5),
 ('b', 2, 'j', 10),
 ('c', 3, 'k', 15),
 ('', '', 'l', 20)]

Use csv.writerows(izip_longest(*lis, fillvalue='')) to write this to a csv file. 使用csv.writerows(izip_longest(*lis, fillvalue=''))将其写入csv文件。

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

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