Save list of ordered tuples as CSV [duplicate]

社会主义新天地 提交于 2019-12-03 04:54:07

问题


I have a list of tuples ordered by value. They are in the form (name,count) where count is number of occurrences for each unique name.

I would like to take this list and transform it into CSV where each name is column header and each value is column value of a single row.

Any suggestions how to do it? Thanks.


回答1:


You can do this:

import csv

data=[('smith, bob',2),('carol',3),('ted',4),('alice',5)]

with open('ur file.csv','wb') as out:
    csv_out=csv.writer(out)
    csv_out.writerow(['name','num'])
    for row in data:
        csv_out.writerow(row)

    # You can also do csv_out.writerows(data) instead of the for loop

the output file will have:

name,num
"smith, bob",2
carol,3
ted,4
alice,5



回答2:


simple google search (Didn't use the Google nose):

Python, transposing a list and writing to a CSV file :

import csv   
lol = [(1,2,3),(4,5,6),(7,8,9)]
item_length = len(lol[0])

with open('test.csv', 'wb') as test_file:
  file_writer = csv.writer(test_file)
  for i in range(item_length):
    file_writer.writerow([x[i] for x in lol])

output

1,4,7
2,5,8
3,6,9


来源:https://stackoverflow.com/questions/15578331/save-list-of-ordered-tuples-as-csv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!