Python:将两个列表写入两列文本文件 [英] Python: Write two lists into two column text file

查看:1444
本文介绍了Python:将两个列表写入两列文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个列表: a = [1,2,3] b = [4,5,6] 我想将它们写入文本文件,以便获得两列文本文件:

Say I have two lists: a=[1,2,3] b=[4,5,6] I want to write them into a text file such that I obtain a two column text file:

1 4
2 5
3 6

推荐答案

简单地zip列表,然后将它们写到以tab为定界符的csv文件中:

Simply zip the list, and write them to a csv file with tab as the delimiter:

>>> a=[1,2,3]
>>> b=[4,5,6]
>>> zip(a,b)
[(1, 4), (2, 5), (3, 6)]
>>> import csv
>>> with open('text.csv', 'w') as f:
...    writer = csv.writer(f, delimiter='\t')
...    writer.writerows(zip(a,b))
...
>>> quit()
$ cat text.csv
1       4
2       5
3       6

这篇关于Python:将两个列表写入两列文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆