2017-08-09 123 views
0

我一直在試圖讓listlistlist寫在python的csv的同一行上。在python中將列表和列表的列表轉換爲csv

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)) 

但我正在逐漸

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

,而不是我要救我的csv如下:

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

請任何可以幫助我解決這個問題?

回答

4

您可以從timestampd添加每個項目到相應的子集:

>>> [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]] 

並且代碼:

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

在Python 3,你可以使用擴展拆包沒有必須創建內部列表:

>>> [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]] 
+0

謝謝。如果我想在'1st'列中加入'timestamp',那麼需要進行什麼樣的更改? – abhi1610

+0

您可以交換參數的順序:'[x + y for * x,y in zip(timestamp,d)]' –

+0

謝謝。但是Python 2.7要做什麼呢?因爲我已經嘗試過'writer.writerows([x + [y] for x,y in zip(t,d)])'仍然會產生錯誤,因爲TypeError:不支持的操作數類型爲+:'float', 'list'' – abhi1610

0

略微不同的方式來解壓您的名單是:

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

這將遍歷行

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

(但基本上是相同的想法在this answer