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

标签 python list file tuples

我有一个元组列表如下:

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)

关于Python - 将元组列表水平写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30656045/

相关文章:

python - 用python或Halcon获取图像的绝对值导数

python - 从日志文件中快速查找行,向后查找,然后逐行读取

list - 查找列表和谓词的任何可能的键合

python - 在 Python 中按位置有效地对坐标点列表进行分组

python - 列表的标准差

perl - 如何从 Perl 中的映射返回哈希引用列表?

linux - 如果 block 设备已经格式化,则退出 mkfs 命令

Android:是否可以使用 openFileOutput 函数创建媒体文件

c - 在 C 中将整数写入文件的最快方法

python - matplotlib 中具有可变长度数据的箱线图