在Python中合并两个列表
我有两个大小相同的列表,现在想把这两个列表合并在一起,并把结果写入一个文件。
alist=[1,2,3,5]
blist=[2,3,4,5]
--合并后的列表应该像这样 [(1,2), (2,3), (3,4), (5,5)]
然后我想把这个结果写入一个文件。请问我该怎么做呢?
2 个回答
13
# 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()
文件中生成的输出将会是:
1,2
2,3
3,4
5,5