在Python中合并2个列表 [英] Combining 2 lists in python
本文介绍了在Python中合并2个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个列表,每个列表大小相等,并且有兴趣将这两个列表合并并将其写入文件.
I have 2 lists each of equal size and am interested to combine these two lists and write it into a file.
alist=[1,2,3,5]
blist=[2,3,4,5]
-结果列表应类似于 [(1,2),(2,3),(3,4),(5,5)]
--the resulting list should be like [(1,2), (2,3), (3,4), (5,5)]
之后,我希望将其写入文件.我该怎么做?
After that i want that to be written it to a file. How can i accomplish this?
推荐答案
# 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
这篇关于在Python中合并2个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文