我現在有三個list 分別如下
co_id = [111,222,333]
year = [90,80,100]
par = [[ㄅ,ㄆ,ㄇ],[A,B,C,D,E],[甲,乙]]
我現在想要將這三個list寫入csv檔裡面
下面是我想呈現的方式
111 90 ㄅ ㄆ ㄇ
222 80 A B C D E
333 100 甲 乙
目前兩個問題分別是:
1.我目前想要在上面空一行,在上面打[ID,年份,句子1,句子2......,句子n],但是不知道該怎麼在第一行依照par的長度去算到句子n的長度
2.目前沒有辦法讓csv呈現我想要的樣子
當我寫下列程式碼時:
with open('test.csv', 'w', newline='',encoding='UTF-8-sig') as test_file:
writer = csv.writer(test_file)
for i in range (0,len(par)):
writer.writerow(par[i])
#會呈現下列情況,但是我不知道該如何加上co_id和year
ㄅ ㄆ ㄇ
A B C D E
甲 乙
但當我寫下列程式碼時:
with open('test.csv', 'w', newline='',encoding='UTF-8-sig') as test_file:
writer = csv.writer(test_file)
for x,y,z in zip (co_id,year,par):
writer.writerow([x,y,z])
#會呈現下列情況,不知道要怎麼將par逐字拆開
111 90 [ㄅ,ㄆ,ㄇ]
222 80 [A,B,C,D,E]
333 100 [甲,乙]
拜託大家幫忙我解決一下了,遭到這問題困擾很久了:(
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
co_id = [111,222,333]
year = [90,80,100]
par = [['ㄅ','ㄆ','ㄇ'],['A','B','C','D','E'],['甲','乙']]
with open('test.csv', 'w', newline='',encoding='UTF-8-sig') as test_file:
writer = csv.writer(test_file, delimiter=' ')
for x,y,z in zip (co_id,year,par):
writer.writerow([x]+[y]+z)
import numpy as np
co_id = [111,222,333]
year = [90,80,100]
par = [["ㄅ","ㄆ","ㄇ"],["A","B","C","D","E"],["甲","乙"]]
co_id_np = np.array(co_id)
year_np = np.array(year)
par_np = np.array([" ".join(i) for i in par])
data = np.array([co_id_np, year_np, par_np])
np.savetxt("sample.csv", data.T, fmt='%s', delimiter='\t')