2016-02-28 88 views
0

好吧,所以我有3个数据列表。每一个都有不同的长度,并且彼此之间没有相关性。需要帮助通过python csv输出

我遇到的问题是,当我去写bList它写入行后aList完成。所以他们都在正确的列中,这是很棒的,但我只是希望每列都从第2行开始(第1行是为标题保留的)。相反,我有一列开始行1和结束28行,然后bList开始29日等

这是我有,我希望你们中的一个罚款向导将解释如何解决它。我明白发生了什么事情导致了这个问题,我只是不知道如何解决这个问题。

def write_output(file): 
    f = open(file, 'w') 
    fields = ('a', 'b', 'c') 
    wr = csv.DictWriter(f, delimiter=",", fieldnames=fields, lineterminator = '\n') 

    wr.writeheader() 
    for row in aList: 
     wr.writerow({'a':row}) 
    for row in bList: 
     wr.writerow({'b':row}) 
    for row in cList: 
     wr.writerow({'c':row}) 
+1

,你必须每行写一行。 –

回答

1

使用zip_longest。

例如,如果你列出不包含None值:

from itertools import zip_longest 

for a_b_c in zip_longest(aList, bList, cList): 
    row = {k: v for k, v in zip(fields, a_b_c) if v is not None} 
    wr.writerow(row) 
+0

完美适用于Python 3.5。 –

0

这里是一个全功能的例子。

此脚本不使用任何库,并在Python 2.7中运行。只需确保每个值都用逗号分隔,就可以创建CSV(逗号分隔值)文件。另外,我不使用itertools,而是使用map函数。

# Python 2.7  
# Here is an example of three lists of different lengths 
aList = [9,8,2,5,14,6] 
bList = [8,7,5,4] 
cList = [9,15,25,60,47,88,3] 

# Creates your empty CSV file 
output_file = open(r'C:\Temp\output.csv', 'w') 

# Adds headers in the first row 
output_file.write('aList,bList,cList\n') 

# Adds all the elements from the lists, row-by-row 
for a, b, c in map(None, aList, bList, cList): 
    output_file.write('%s,%s,%s\n' % (a, b, c)) 

# Closes your file 
output_file.close() 

Python 3中,map功能不再支持None是一个映射函数。在这种情况下,从itertoolszip_longest功能可能是你不能写每个元素的CSV元素最干净的方法(注意,在Python 2.7,从itertools这个函数被调用izip_longest

# Python 3.x 
import itertools 

# Here is an example of three lists of different lengths 
aList = [9,8,2,5,14,6] 
bList = [8,7,5,4] 
cList = [9,15,25,60,47,88,3] 

# Creates your empty CSV file 
output_file = open(r'C:\Temp\output.csv', 'w') 

# Adds headers in the first row 
output_file.write('aList,bList,cList\n') 

# Adds all the elements from the lists, row-by-row 
for a, b, c in itertools.zip_longest(aList, bList, cList): 
    output_file.write('%s,%s,%s\n' % (a, b, c)) 

# Closes your file 
output_file.close() 
+0

TypeError:'NoneType'对象不可调用 这是在Python 3.5中 –

+0

必须使用itertools.zip_longest,但我宁愿按照自己的方式做,因为没有依赖关系。 –

+0

我更喜欢外部库的数量最少的脚本。 'itertools'是Python的一个内置库。我用“Python 3.x”解决方案编辑了我的回复。 –