我有一些像这样的清单:
[['CD', 'CC', 'CD'], 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[['DT', 'CC', 'CD'], 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1]
[['EX', 'CC', 'CD'], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[['JJ', 'CC', 'CD'], 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1]
我希望将这些列表明确地写入csv文件列。到目前为止我做了什么:
for i in range(1,840):
# function which compute the result value
result=Count_SP(i,leng_second,first_position+1,second_position)
final.append(result)
print final # final contains lists
File_Write(final) # File_Write() writes the final into a csv file
需要输出:
['CD', 'CC', 'CD'],['DT', 'CC', 'CD'],['EX', 'CC', 'CD'],['JJ', 'CC', 'CD']
1,0,0,0
1,0,0,0
1,1,0,1
1,0,0,0
1,1,0,1
1,0,0,0
1,1,0,1
1,1,0,1
1,1,0,0
1,1,0,1
1,1,0,1
1,1,0,1
答案 0 :(得分:2)
如果您将列表放在容器中,那么实际上非常简单:
import csv
container = [[['CD', 'CC', 'CD'], 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[['DT', 'CC', 'CD'], 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1],
[['EX', 'CC', 'CD'], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[['JJ', 'CC', 'CD'], 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1]]
with open('out.csv', 'w') as csvfile:
csvw = csv.writer(csvfile, delimiter=',')
for column in zip(*[s for s in container]):
csvw.writerow(column)
这将创建文件out.csv
,该列将包含输入列表:
"['CD', 'CC', 'CD']","['DT', 'CC', 'CD']","['EX', 'CC', 'CD']","['JJ', 'CC', 'CD']"
1,0,0,0
1,0,0,0
1,1,0,1
1,0,0,0
1,1,0,1
1,0,0,0
1,1,0,1
1,1,0,1
1,1,0,0
1,1,0,1
1,1,0,1
1,1,0,1