Q:

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

suppose I have an numpy array with structure like this:
[['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
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?

A:

Use 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.

