我有一个元组列表如下:
with open(...) as f:
for line in f:
# add the line in the set
我想将此列表写入文件,如下所示:
listo = [ (A,1),(B,2),(C,3) ]
我尝试了以下内容,它输出如下:
A B C
1 2 3
我尝试在f.write函数中切换\ t和\ n,并使用格式化功能。没有任何效果。
我在这里想念的是什么?
答案 0 :(得分:4)
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)
答案 1 :(得分:1)
其中一种方法是将每个元组中的两个元素分成两个不同的列表(或元组)
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))
答案 2 :(得分:1)
您需要先转置/解压缩列表。这是通过习语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
答案 3 :(得分:0)
尝试单独循环:
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
答案 4 :(得分:0)
>>> 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')
...