如何从多个列表制作CSV文件? [英] How to make a CSV file from a number of lists?
本文介绍了如何从多个列表制作CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用列表制作一个CSV文件
I am trying to make a csv file using the lists
['2005-04-18', '2005-04-19', '2005-04-20']
['1', '1', '1']
['0.7683', '0.766664', '0.764696']
['1.380162', '1.373308', '1.358544']
第一列中的日期和行中的相应值
with the dates in the first column and the corresponding values across the rows
我已经有
with open((os.path.join('data','hist', 'rates-'+date1+' to ' +date2+ '.csv')), 'wt') as my_csv:
csv_writer = csv.writer(my_csv, lineterminator='\n')
csv_writer.writerow(["Date",curr1, curr2, curr3])
这给了我带有标题的文件。我该如何完成呢?
which gives me the file with the headers. How can I finish this?
推荐答案
您使用循环来处理所拥有的数组的元素。
You use a loop to process the elements of the arrays that you have.
a = ['2005-04-18', '2005-04-19', '2005-04-20']
b = ['1', '1', '1']
c = ['0.7683', '0.766664', '0.764696']
d = ['1.380162', '1.373308', '1.358544']
您可以使用 zip
创建元组从列表中写出:
You can use zip
to create tuples from the lists and write those:
for row in zip(a, b, c, d):
csv_writer.writerow(row)
或者您也可以自己设置字符串格式并将其打印到文件中(无需使用csv_writer):
Or you can just youse string formatting and print it into the file yourself (without using csv_writer):
for i in range(len(a)):
csv_writer.writerow('{}, {}, {}, {}'
.format(a[i], b[i], c[i], d[i]))
这篇关于如何从多个列表制作CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文