2016-02-28 90 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」解決方案編輯了我的回覆。 –