我有一长串这样的表格——

a = [[1.2,'abc',3],[1.2,'werew',4],........,[1.4,'qew',2]]

也就是说,列表中的值是不同类型的——float,int, strings。我如何将它写入csv文件,使我的输出csv文件看起来像这样

1.2,abc,3
1.2,werew,4
.
.
.
1.4,qew,2

当前回答

在将列表的列表的列表的列表导出为.csv的情况下,这将在Python3中工作:

import csv
with open("output.csv", "w") as f:
    writer = csv.writer(f)
    for element in lll:
        writer.writerows(element)

其他回答

使用csv。在我庞大的列表中,作者花了相当长的时间。我决定使用熊猫,它更快,更容易控制和理解:

 import pandas

 yourlist = [[...],...,[...]]
 pd = pandas.DataFrame(yourlist)
 pd.to_csv("mylist.csv")

好的部分是你可以改变一些东西来创建一个更好的csv文件:

 yourlist = [[...],...,[...]]
 columns = ["abcd","bcde","cdef"] #a csv with 3 columns
 index = [i[0] for i in yourlist] #first element of every list in yourlist
 not_index_list = [i[1:] for i in yourlist]
 pd = pandas.DataFrame(not_index_list, columns = columns, index = index)

 #Now you have a csv with columns and index:
 pd.to_csv("mylist.csv")

如果您不想为此导入csv模块,您可以只使用Python内置程序将列表的列表写入csv文件

with open("output.csv", "w") as f:
    for row in a:
        f.write("%s\n" % ','.join(str(col) for col in row))

在将列表的列表的列表的列表导出为.csv的情况下,这将在Python3中工作:

import csv
with open("output.csv", "w") as f:
    writer = csv.writer(f)
    for element in lll:
        writer.writerows(element)

Ambers的解决方案也适用于numpy数组:

from pylab import *
import csv

array_=arange(0,10,1)
list_=[array_,array_*2,array_*3]
with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(list_)
import csv
with open(file_path, 'a') as outcsv:   
    #configure writer to write standard csv file
    writer = csv.writer(outcsv, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
    writer.writerow(['number', 'text', 'number'])
    for item in list:
        #Write item to outcsv
        writer.writerow([item[0], item[1], item[2]])

官方文档:http://docs.python.org/2/library/csv.html