Python 将有序元组列表保存为 CSV

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15578331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:27:15  来源:igfitidea点击:

Save list of ordered tuples as CSV

pythoncsvtuples

提问by Edmon

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.

我有一个按值排序的元组列表。它们采用以下形式(name,count),其中 count 是每个唯一名称的出现次数。

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.

我想把这个列表转换成 CSV,其中每个名称都是列标题,每个值都是单行的列值。

Any suggestions how to do it? Thanks.

任何建议如何做到这一点?谢谢。

采纳答案by dawg

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

回答by 0x90

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

简单的谷歌搜索(没有使用谷歌鼻子):

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

Python,转置列表并写入 CSV 文件

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

The above is for python 2.

以上是针对python 2的。

Trying it in python 3 might give the error as mentioned in TypeError: a bytes-like object is required, not 'str' in python and CSV.

在 python 3 中尝试它可能会给出TypeError 中提到的错误:需要一个类似字节的对象,而不是 python 和 CSV 中的 'str'

The above linked question has an answer which directs us to use

上面链接的问题有一个答案,指导我们使用

with open('ur file.csv','w') as out:for python 3.

with open('ur file.csv','w') as out:对于蟒蛇 3。