在Python中合并两个列表

3
我有两个等长的列表,想将它们合并并写入文件。
alist=[1,2,3,5] 
blist=[2,3,4,5] 

--结果列表应该像这样[(1,2), (2,3), (3,4), (5,5)]。 之后,我想把它写入文件。我该如何完成这个任务?

1
请删除第一条语句末尾的逗号。目前alist是一个元组,其值为([1, 2, 3, 5],) - Stephan202
1
重复:http://stackoverflow.com/questions/803526/merge-two-lists-of-lists-python。看起来像是作业。肯定是一个常见问题。 - S.Lott
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

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))

The documentation for izip can be found here.


2
好的观点;如果您使用2.6或更早版本,则值得这样做。在Python 3中,zip()生成一个迭代器而不是列表。 - Ben James
@Ben:是的,你说得对!我没有提到Python 3,但这也值得知道。 - RedGlyph

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接