简体   繁体   English

将列表列表另存为csv文件python中的行

[英]Save list of lists as rows in csv file python

I have a list of lists as follows: 我有一个列表列表,如下所示:

L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I want to save this in a csv file as follows: 我要将其保存在csv文件中,如下所示:

index, name, lists

0, 'name1', [1, 2, 3]
1, 'name2', [4, 5, 6]
2, 'name3', [7, 8, 9]

If this is possible, then how should I do this with python? 如果有可能,那我应该如何用python做到这一点?

If you leave the default kwargs for csv.writer it will recognize that the list has commas in the string representation of the list and automatically quote it for you. 如果您将默认的kwargs 留给csv.writer ,它将识别出列表的字符串表示形式中包含逗号,并自动为您引用。

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

If you look at filename.csv you get 如果您查看filename.csv您将获得

index,name,lists
0,name_0,"[1, 2, 3]"
1,name_1,"[4, 5, 6]"
2,name_2,"[7, 8, 9]"

You can use Pandas to assemble your data into a data frame and easily output it as a CSV file: 您可以使用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]

You only have 3 rows in your sheet, is that correct? 工作表中只有3行,对吗? If so, Pandas.DataFrame would be a great fit for this issue. 如果是这样,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)

If you try to print the result, it will show like following (apologize I don't know how to embed the table properly) 如果您尝试打印结果,它将显示如下(对不起,我不知道如何正确嵌入表格)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM