Combining 2 lists in python

I have 2 lists of each of equal size, and I am interested in combining these two lists and writing them to a file.

alist=[1,2,3,5] 
blist=[2,3,4,5] 

- the resulting list should look like [(1,2), (2,3), (3,4), (5,5)]

After that, I want it to be written to a file. How can i do this?

+3
source share
2 answers
# combine the lists
zipped = zip(alist, blist)

# write to a file (in append mode)
file = open("filename", 'a') 
for item in zipped:
    file.write("%d, %d\n" % item) 
file.close()

The resulting result in the file will be:

 1,2
 2,3
 3,4
 5,5
+13
source

For completeness, I will add Ben> to the solution, which is itertools.izippreferable, especially for larger lists, if the result is used iteratively, the final result is not an actual list, but a generator:

from itertools import izip
zipped = izip(alist, blist)
with open("output.txt", "wt") as f:
    for item in zipped:
        f.write("{0},{1}\n".format(*item))

izip .

+6

Source: https://habr.com/ru/post/1721869/


All Articles