0

I have two lists in Python: 'away' and '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:

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

1
  • Do you mean a row or column? And what have you tried so far - can you show us some code? Commented Nov 15, 2014 at 22:01

2 Answers 2

2

Looks like you just want the useful and flexible zip built-in.

>>> away = ["away1", "away2", "away3"]
>>> home = ["home1", "home2", "home3"]
>>> list(zip(away, home))
[('away1', 'home1'), ('away2', 'home2'), ('away3', 'home3')]
Sign up to request clarification or add additional context in comments.

Comments

0
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.

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.