Skip to main content
 首页 » 编程设计

Python之将元组列表水平写入文本文件

2025年05月04日14xing901022

我有一个元组列表如下:

listo = [ (A,1),(B,2),(C,3) ] 

我想将此列表写入如下文件:

A   B   C 
1   2   3 

我尝试了以下方法,结果如下:

with open('outout.txt', 'w') as f: 
    for x, y in listo: 
        f.write("{0}\t{1}\n".format(x,y) 
 
A   1 
B   2 
C   3 

我尝试在 f.write 函数中切换\t 和\n 并尝试使用 format 函数。没有任何效果。

我在这里错过了什么?

请您参考如下方法:

The csv module在这里肯定可以帮助您:

首先,通过调用 zip 来分离 header 和值。然后使用 csv

将它们写入您的文件
In [15]: listo 
Out[15]: [('A', 1), ('B', 2), ('C', 3)] 
 
In [16]: headers, vals = zip(*listo) 
 
In [17]: headers 
Out[17]: ('A', 'B', 'C') 
 
In [18]: vals 
Out[18]: (1, 2, 3) 

完整的解决方案:

import csv 
 
listo = [(A,1), (B,2), (C,3)] 
headers, vals = zip(*listo) 
 
with open('output.txt', 'w') as outfile: 
    writer = csv.writer(outfile, delimiter='\t') 
    writer.writerow(headers) 
    writer.writerow(vals)