我有一个列表列表,如下所示:
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
我要将其保存为csv文件,如下所示:
index, name, lists
0, 'name1', [1, 2, 3]
1, 'name2', [4, 5, 6]
2, 'name3', [7, 8, 9]
如果可能的话,那我应该如何用python做到这一点?
答案 0 :(得分:1)
如果您为csv.writer保留默认kwarg,它将识别出列表的字符串表示形式中包含逗号,并自动为您引用。
import csv
with open('filename.csv', 'w') as f:
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
fieldnames = ['index', 'name', 'lists']
writer = csv.writer(f)
writer.writerow(fieldnames)
for i, row in enumerate(L):
writer.writerow([str(i), 'name{}'.format(i), row])
如果您看到filename.csv
,将会得到
index,name,lists
0,name_0,"[1, 2, 3]"
1,name_1,"[4, 5, 6]"
2,name_2,"[7, 8, 9]"
答案 1 :(得分:1)
您可以使用Pandas将数据组合到数据框中并轻松将其输出为CSV文件:
import pandas as pd
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
name = ['name1', 'name2', 'name3']
df = pd.DataFrame({'name': name, 'lists': L})
print(df)
df.to_csv('file.csv', index_label='index')
name lists
0 name1 [1, 2, 3]
1 name2 [4, 5, 6]
2 name3 [7, 8, 9]
答案 2 :(得分:1)
工作表中只有3行,对吗? 如果是这样,Pandas.DataFrame将非常适合此问题。
#import pandas moudle first
import pandas as pd
#If you want to add `index` as the column name
index=[0,1,2]
name =['name 0','name 1','name 2']
#This is your original list in Python
L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#Using pd.DataFrame function to reformat the list into table
#Name the first column as 'index', the second column as 'name', and the last column as'lists'
table = pd.DataFrame({'index':index,
'name':name,
'lists':L})
#Write DataFrame to a comma-separated values (csv) file
table.to_csv('L.csv', index=False)
如果您尝试打印结果,它将显示如下(对不起,我不知道如何正确嵌入表格)
<table>
<tr>
<td></td>
<td>index</td>
<td>name</td>
<td>list</td>
</tr>
<tr>
<td>0</td>
<td>0</td>
<td>name 1</td>
<td>[1, 2, 3]</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>name 2</td>
<td>[4, 5, 6]</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>name 3</td>
<td>[7, 8, 9]</td>
</tr>
</table>