简体   繁体   English

将嵌套列表逐列写入CSV

[英]Write nested lists column wise to CSV

I have some list like so: 我有一些像这样的列表:

[['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]

And I want write these list into a csv file column wise. 我希望将这些列表明确地写入csv文件列。 What I did so far: 到目前为止我做了什么:

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

Output needed: 需要的输出:

['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

If you put your lists in a container then it's actually quite simple: 如果您将列表放在容器中,那么它实际上非常简单:

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)

This create the file out.csv which will contain the input lists column wise: 这将创建文件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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM