abhi1610
abhi1610

Reputation: 743

Convert list of list and list to csv in python

I have been trying to get listoflist and list to be written on same row on csv in python.

d=[[1,2,3,4,5,6],[2,3,4,5,6,7]]
timestamp = [0.1, 0.3] # Basically timestamping for each list of d
file = open('test.csv', 'w')
writer = csv.writer(file, delimiter=',',lineterminator='\n')
writer.writerows(zip(d, timestamp)) 

But I am getting

col1         , col2
[1,2,3,4,5,6], 0.1
[2,3,4,5,6,7], 0.3

instead I want to save my csv as follows:

col1,col2, ...,col7
1,2,3,4,5,6, 0.1
2,3,4,5,6,7, 0.3

Please any can help me with this problem?

Upvotes: 0

Views: 317

Answers (2)

hiro protagonist
hiro protagonist

Reputation: 46859

a slightly different way to unpack your lists is this:

writer.writerows((*a, b) for a, b in zip(d, timestamp))

this will iterate over the rows

(1, 2, 3, 4, 5, 6, 0.1)
(2, 3, 4, 5, 6, 7, 0.3)

(but basically the same idea as in this answer)

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78556

You can add each item from the timestamp to the corresponding sublist in d:

>>> [x+[y] for x, y in zip(d, timestamp)]
[[1, 2, 3, 4, 5, 6, 0.1], [2, 3, 4, 5, 6, 7, 0.3]]

And your code becomes:

...
writer.writerows(x+[y] for x, y in zip(d, timestamp)) 

In Python 3, you can use extended unpacking without having to create the inner list:

>>> [x+y for x, *y in zip(d, timestamp)]
[[1, 2, 3, 4, 5, 6, 0.1], [2, 3, 4, 5, 6, 7, 0.3]]

Upvotes: 4

Related Questions