在Python中合并两个列表

3 投票
2 回答
1534 浏览
提问于 2025-04-15 15:39

我有两个大小相同的列表,现在想把这两个列表合并在一起,并把结果写入一个文件。

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

--合并后的列表应该像这样 [(1,2), (2,3), (3,4), (5,5)]

然后我想把这个结果写入一个文件。请问我该怎么做呢?

2 个回答

6

为了完整起见,我想补充一下Ben的解决方案,就是如果你要处理比较大的列表,使用itertools.izip会更好,特别是当你是逐步使用结果的时候,因为最后得到的结果并不是一个真正的列表,而是一个生成器:

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的文档可以在这里找到。

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

撰写回答