Python 如何将两个列表中的数据写入 csv 中的列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19302612/
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
How to write data from two lists into columns in a csv?
提问by Nathan Thomas
I want to write data that I have to create a histogram into a csv file. I have my 'bins' list and I have my 'frequencies' list. Can someone give me some help to write them into a csv in their respective columns?
我想将创建直方图的数据写入 csv 文件。我有我的“垃圾箱”列表和我的“频率”列表。有人可以帮我将它们写入各自列中的 csv 吗?
ie bins in the first column and frequency in the second column
即第一列中的 bins 和第二列中的频率
采纳答案by Ludwik Trammer
The original Python 2 answer
原始的 Python 2 答案
This example uses izip
(instead of zip
) to avoid creating a new list and having to keep it in the memory. It also makes use of Python's built in csv module, which ensures proper escaping. As an added bonus it also avoids using any loops, so the code is short and concise.
此示例使用izip
(而不是zip
) 来避免创建新列表并将其保留在内存中。它还利用Python 的内置 csv 模块,确保正确的转义。作为一个额外的好处,它还避免使用任何循环,因此代码简洁明了。
import csv
from itertools import izip
with open('some.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerows(izip(bins, frequencies))
The code adapted for Python 3
适用于 Python 3 的代码
In Python 3, you don't need izip
anymore—the builtin zip
now does what izip
used to do. You also don't need to open the file in binary mode:
在 Python 3 中,您不再需要izip
了 — 内置zip
函数现在可以完成以前的工作izip
。您也不需要以二进制模式打开文件:
import csv
with open('some.csv', 'w') as f:
writer = csv.writer(f)
writer.writerows(zip(bins, frequencies))
回答by Pixou
you should use zip() http://docs.python.org/2/library/functions.html#zip
你应该使用 zip() http://docs.python.org/2/library/functions.html#zip
something like :
就像是 :
f=open(my_filename,'w')
for i,j in zip(bins,frequencies):
f.write(str(i)+","+str(j))
f.close()
回答by DirkR
Hm, am I missing something? This sounds pretty straightforward:
嗯,我错过了什么吗?这听起来很简单:
bins = [ 1,2,3,4,5 ]
freq = [ 9,8,7,6,5 ]
f = open("test.csv", "w")
for i in xrange(len(bins)):
f.write("{} {}\n".format(bins[i], freq[i]))
f.close()