2016-10-03 56 views
2

使用Python,我有存儲在列表中的數據:的Python:寫列表到CSV,調換第一行成列

a = [['a', 'b', 'c'], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] 

我想寫這個列表到CSV,看起來像下面這樣:

a, 1, 2, 3, 4 
b, 5, 6, 7, 8 
c, 9, 10, 11, 12 

這是我閱讀大量的其他變調問題後與上前代碼:

length = len(a[0]) 
with open('test.csv', 'w') as test_file: 
    file_writer = csv.writer(test_file) 
    for i in range(length): 
     file_writer.writerow([x[i] for x in a]) 

瓦ICH給我:

a,1,5,9 
b,2,6,10 
c,3,7,11 

所以調換整個列表(更不用提一些值甚至可以輸),但如上圖所示,我只想要調換的第一行。我只是不知道該把手放在哪裏。

感謝Nf4r,我想出了下面的 - 可能看起來笨拙,但工程:-)

a = [['a', 'b', 'c'], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] 
f = open('test.csv', 'a') 
for header, data in zip(a[0], a[1:]): 
    result = "{header}, {data}".format(header = header, 
           data = ', '.join((str(n) for n in data))) 
    f.write(result) 
    f.write('\n') 
f.close() 
+1

歡迎來到StackOverflow。請把你到目前爲止嘗試過的代碼放在一邊,因爲你沒有嘗試,所以我已經低估了你的問題。 – DhruvPathak

+0

是的,提供更多的代碼。如果你能重組你的數據結構'a',請考慮一下。也許使用一個字典:'{「a」:[1,2,3,4]; 「b」:[5,6,7,8] .....'。這將使解決方案變得更容易。 – buhtz

+1

@DhruvPathak +1:他做到了! –

回答

0

你只需要拉頭子列表zip其餘使用編者合併成單個列表後:

a = [['a', 'b', 'c'], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] 
import csv 

with open('test.csv', 'w') as test_file: 
    file_writer = csv.writer(test_file) 
    it = iter(a) 
    col_1 = next(it) 
    file_writer.writerows([a] + b for a,b in zip(col_1, it)) 
+0

是的!這是我想要做的,但我無法到達那裏。感謝您的幫助。 – l3y

0

也許是這樣的:

a = [['a', 'b', 'c'], [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] 

for header, data in zip(a[0], a[1:]): 
    result = "{header}, {data}".format(header= header, 
             data= ', '.join((str(n) for n in data))) 
    print(result) 
a, 1, 2, 3, 4 
b, 5, 6, 7, 8 
c, 9, 10, 11, 12 
<do what u want with it> 
+0

不客氣。 – Nf4r

+0

再次感謝,我不知道如何在這裏發佈代碼,所以我只是把它放在主帖子中。 – l3y