简体   繁体   English

从Python的两个列表中逐行追加csv?

[英]Append csv by row from two lists in Python?

I have two lists in Python: 'away' and 'home'. 我在Python中有两个列表:“ away”和“ home”。 I want to append them to an already existing csv file such that I write a row solely of 1st element of away, then 1st element of home, then the 2nd element of away, then the 2nd element of home,...etc with empty spaces in between them, so it will be like this: 我想将它们附加到一个已经存在的csv文件中,这样我就只写了away的第一个元素,然后home的第一个元素,然后away的第二个元素,然后home的第二个元素,...等一行,用空它们之间有空格,所以会像这样:

away1
home1

away2
home2

away3
home3

and so on and so on. 等等等等。 The size of the away and home lists is the same, but might change day to day. 离开清单和家庭清单的大小相同,但可能会每天变化。 How can I do this? 我怎样才能做到这一点?

Thanks 谢谢

Looks like you just want the useful and flexible zip built-in. 看起来您只想要有用且灵活的内置zip

>>> away = ["away1", "away2", "away3"]
>>> home = ["home1", "home2", "home3"]
>>> list(zip(away, home))
[('away1', 'home1'), ('away2', 'home2'), ('away3', 'home3')]
import csv

away = ["away1", "away2", "away3"]
home = ["home1", "home2", "home3"]
record_list = [ list(item) for item in list(zip(away, home)) ]
print record_list
with open("sample.csv", "a") as fp:
    writer = csv.writer(fp)
    writer.writerows(record_list)

# record_list =  [['away1', 'home1'], ['away2', 'home2'], ['away3', 'home3']]

You should use writerows method to write multiple list at a time to each row. 您应该使用writerows方法一次将多个列表写入每一行。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM