简体   繁体   English

在python中组合2个列表

[英]Combining 2 lists in python

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] 

--the resulting list should be like [(1,2), (2,3), (3,4), (5,5)] - 结果列表应该像[(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()

The resulting output in the file will be: 文件中的结果输出将是:

 1,2
 2,3
 3,4
 5,5

For the sake of completeness, I'll add to Ben's solution that itertools.izip is preferable especially for larger lists if the result is used iteratively, as the final result is not an actual list but a generator: 为了完整起见,我将添加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 . 可以在这里找到izip的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM