使用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()
歡迎來到StackOverflow。請把你到目前爲止嘗試過的代碼放在一邊,因爲你沒有嘗試,所以我已經低估了你的問題。 – DhruvPathak
是的,提供更多的代碼。如果你能重組你的數據結構'a',請考慮一下。也許使用一個字典:'{「a」:[1,2,3,4]; 「b」:[5,6,7,8] .....'。這將使解決方案變得更容易。 – buhtz
@DhruvPathak +1:他做到了! –