将每个列表写入csv表中的列 [英] Write each list as a column in csv table

查看:147
本文介绍了将每个列表写入csv表中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个列表,每个列表包含字符串,我想填充csv表。我想要每个列表在其各自的列标题中是一个单独的数据列。标题行是与outrow变量相同的序列。使用下面的代码,只需填充所有列表中的所有数据的第一列。

I have multiple lists with each list containing strings that I want to fill in a csv table. I want each list to be a separate column of data in its respective column header. The header row is the same sequence as the outrow variable. With the code below it simply just fills in the first column with all the data from all the lists.

#outrow = (Layer,RasterCatalog,ShapeFile,Text,Terrain,GroupLayer,Locator,MapDocument,Toolbox,DbaseTable,RasterDataset)

#formats = (['Layer','RasterCatalog','ShapeFile','Text','Terrain','GroupLayer','Locator','MapDocument','Toolbox','DbaseTable','RasterDataset'])

# if I were to print(outrow), it would look like this:
   #(['H:\\Test\\Test_Data\\New Layer.lyr'], [], ['H:\\Test\\Test_Data\\New_Shapefile.dbf', 'H:\\Test\\Test_Data\\New_Shapefile.shp'], [], [], [], [], [], [], ['H:\\Test\\Test_Data\\New_dBASE_Table.dbf'], [])

def WriteCSVFile(csvFile,formats,outrow):

    ofile  = open(csvFile, "wb")        
    writer = csv.writer(ofile, delimiter=',')
    writer.writerow(formats) #making header here
    writer.writerows(outrow)
    ofile.close()


推荐答案

如果我正确理解你的话, outrow 是一个列表列表,其中每个列表包含一列,对吧?然后(假设他们都是相同的长度),你可以简单地 zip()他们在一起:

If I understand you correctly, then outrow is a list of lists, where each list contains one column, right? Then (assuming that they are all of the same length) you can simply zip() them together:

writer.writerows(zip(*outrow))

>>> outrow = [[1,2,3], [4,5,6], [7,8,9]]
>>> import csv
>>> import sys
>>> w = csv.writer(sys.stdout)
>>> w.writerows(zip(*outrow))
1,4,7
2,5,8
3,6,9

如果列的长度不同,请使用 izip_longest() //docs.python.org/2/library/itertools.htmlrel =nofollow> itertools 模块 zip_longest )如果你使用Python 3):

If the columns are of different length, use izip_longest() from the itertools module (zip_longest() if you're on Python 3):

>>> import itertools
>>> outrow = (['H:\\Test\\Test_Data\\New Layer.lyr'], [], ['H:\\Test\\Test_Data\\New_Shapefile.dbf', 'H:\\Test\\Test_Data\\New_Shapefile.shp'], [], [], [], [], [], [], ['H:\\Test\\Test_Data\\New_dBASE_Table.dbf'], [])
>>> w.writerows(itertools.izip_longest(*outrow, fillvalue=""))
H:\Test\Test_Data\New Layer.lyr,,H:\Test\Test_Data\New_Shapefile.dbf,,,,,,,H:\Test\Test_Data\New_dBASE_Table.dbf,,,H:\Test\Test_Data\New_Shapefile.shp,,,,,,,,

这篇关于将每个列表写入csv表中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆