在python中将列表和列表转换为csv

2024-10-02 10:28:39 发布

您现在位置:Python中文网/ 问答频道 /正文

{{cd1>

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

但我得到了

^{pr2}$

相反,我想保存我的csv,如下所示:

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

有谁能帮我解决这个问题吗?在


Tags: ofcsvtestforopentimestamplistfile
2条回答

另一种稍微不同的方法是:

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

这将迭代行

^{pr2}$

(但基本上与this answer中的想法相同)

您可以将timestamp中的每个项目添加到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]]

你的代码变成:

^{pr2}$

在Python3中,您可以使用扩展解包,而不必创建内部列表:

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

相关问题 更多 >

    热门问题