Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

python - How to write data from two lists into columns in a csv?

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?

ie bins in the first column and frequency in the second column

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The original Python 2 answer

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.

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

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:

import csv

with open('some.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerows(zip(bins, frequencies))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...