我有一个元组列表,如下所示:
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,并使用格式函数。毫无效果。
我在这里错过了什么?
csv
模块当然可以在这里帮助您:
首先,通过调用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)
一种方法是将每个元组中的两个元素分隔成两个不同的列表(或元组)
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))
首先需要对列表进行转置/解压缩。这是用习惯用法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
试着分开循环:
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')
...