Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 931
LWZ Avatar asked Oct 22 '13 06:10

LWZ


People also ask

Which function is suitable to write a nested list into a csv file?

The most common method to write data from a list to CSV file is the writerow() method of writer and DictWriter class.

Does CSV use nesting?

Too bad because CSV format doesn't do "nested".

How do I read all lines in a csv file in Python?

Step 1: In order to read rows in Python, First, we need to load the CSV file in one object. So to load the csv file into an object use open() method. Step 2: Create a reader object by passing the above-created file object to the reader function. Step 3: Use for loop on reader object to get each row.


1 Answers

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.

like image 106
Ashwini Chaudhary Avatar answered Nov 15 '22 15:11

Ashwini Chaudhary