Reputation: 743
I have been trying to get list
oflist
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
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
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