3

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. 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
0

1 Answer 1

2

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:

"['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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.