简体   繁体   中英

Python - Write list of tuples horizontally to a text file

I have a list of tuples as follows:

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

I want to write this list to a file as below:

A   B   C
1   2   3

I tried the following and it gave the output as below:

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

I tried switching up the \\t and \\n in f.write function and also played with the format function. Nothing worked.

What did I miss here?

The csv module can certainly help you out here:

First, separate out the headers and the values with a call to zip . Then write them out to your file with 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)

The full solution:

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)

One of the ways is to seperate the two elements in each tuple into two different lists (or tuples)

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))

Or you can use 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))

You need to transpose/unzip the list first. This is done with the idiom 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)

File output.txt :

A   B   C
1   2   3

Just try doing separate loops:

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
>>> 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')
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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