【问题标题】:Python - Write list of tuples horizontally to a text filePython - 将元组列表水平写入文本文件
【发布时间】:2015-06-04 23:44:48
【问题描述】:

我有一个元组列表如下:

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 函数。没有任何效果。

我错过了什么?

【问题讨论】:

  • 元组中是否只有两个元素?

标签: python list file tuples


【解决方案1】:

The csv module 当然可以在这里为您提供帮助:

首先,通过调用zip 将标头和值分开。然后用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)

【讨论】:

  • 更笼统地说:writer.writerows(zip(*listo))
【解决方案2】:

其中一种方法是将每个元组中的两个元素分成两个不同的列表(或元组)

with open('outout.txt', 'w') as f:
    for x, y in listo:
        f.write("{}\t".format(x))
    f.write("\n")
    for x, y in listo:
        f.write("{}\t".format(y))

或者你可以使用join

a = "\t".join(i[0] for i in listo)
b = "\t".join(i[1] for i in listo)
with open('outout.txt', 'w') as f:
    f.write("{}\n{}".format(a,b))

【讨论】:

  • 哦哦...加入。肯定更好。 :)
【解决方案3】:

您需要先转置/解压缩列表。这是通过成语zip(*list_) 完成的。

# For Python 2.6+ (thanks iCodez):
# from __future__ import print_function

listo = [("A", 1), ("B", 2), ("C", 3)]
transposed = zip(*listo)
letters, numbers = transposed

with open("output.txt", "w") as output_txt:
    print(*letters, sep="\t", file=output_txt)
    print(*numbers, sep="\t", file=output_txt)

文件output.txt

A   B   C
1   2   3

【讨论】:

【解决方案4】:

尝试做单独的循环:

with open('outout.txt', 'w') as f:
for x in listo:
    f.write('{}\t'.format(x[0])) # print first element with tabs
f.write('\n') # print a new line when finished with first elements
for y in listo:
    f.write('{}\t'.format(x[1])) # print second element with tabs
f.write('\n') # print another line

【讨论】:

    【解决方案5】:
    >>> A = 'A'
    >>> B = 'B'
    >>> C = 'C'
    >>> listo = [ (A,1),(B,2),(C,3) ]
    >>> print(*zip(*listo))
    ('A', 'B', 'C') (1, 2, 3)
    >>> print(*('\t'.join(map(str, item)) for item in zip(*listo)), sep='\n')
    A       B       C
    1       2       3
    >>> with open('outout.txt', 'w') as f:
    ...     for item in zip(*listo):
    ...         f.write('\t'.join(map(str, item)) + '\n')
    ...
    

    【讨论】:

      猜你喜欢
      • 2016-09-07
      • 2023-03-15
      • 2021-08-06
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      • 2014-11-22
      • 2013-02-18
      • 1970-01-01
      相关资源
      最近更新 更多