I have two lists that are already sorted how they need to be, and i need them put into one file, like this example:
list1 = [a, b, c, d, e]
list2 = [1, 2, 3, 4, 5]
output file should look like:
a1
b2
c3
d4
e5
im fairly new to python, so im not really all that sure how to do file writing. I read using with open(file, 'w') as f: is a better/easier way to start the writing block, but i am unsure how to merge the lists and print them as such. I could probably merge them into a third list and print that one to the file using print>>f, item but i wanted to see if there was as simpler way.
Thank you!
Late edit: looking at my lists, they wont always be the same length, but all the data needs printed regardless. So if list2 went to 7 then then the output would need to be:
a1
b2
c3
d4
e5
6
7
or vice versa, where list1 may be longer then list2.
Use the zip() function to combine (ie zip) your two lists. E.g.,
gives:
you can then format the output to suit your needs.
yielding:
Update:
If your lists are unequal length, this approach using
itertools.izip_longest() might work for you:
gives:
Note, if you were using Python 3, there is a nice way to use the
print()function. I am usingwrite()here to avoid extra blank spaces between items.