【发布时间】:2010-02-22 04:54:06
【问题描述】:
我的 Python 模块有一个列表,其中包含我想在某处保存为 .txt 文件的所有数据。该列表包含几个元组,如下所示:
list = [ ('one', 'two', 'three'), ('four', 'five', 'six')]
如何打印列表,以便每个元组项目由制表符分隔,每个元组由换行符分隔?
谢谢
【问题讨论】:
标签: python list csv export tuples
我的 Python 模块有一个列表,其中包含我想在某处保存为 .txt 文件的所有数据。该列表包含几个元组,如下所示:
list = [ ('one', 'two', 'three'), ('four', 'five', 'six')]
如何打印列表,以便每个元组项目由制表符分隔,每个元组由换行符分隔?
谢谢
【问题讨论】:
标签: python list csv export tuples
您可以解决它,正如其他答案所建议的那样,只需加入行,但更好的方法是使用 python csv 模块,以便稍后您可以轻松更改分隔符或添加标题等并将其读回,看起来像您想要制表符分隔文件
import sys
import csv
csv_writer = csv.writer(sys.stdout, delimiter='\t')
rows = [ ('one', 'two', 'three'), ('four', 'five', 'six')]
csv_writer.writerows(rows)
输出:
one two three
four five six
【讨论】:
print '\n'.join('\t'.join(x) for x in L)
【讨论】:
试试这个
"\n".join(map("\t".join,l))
测试
>>> l = [ ('one', 'two', 'three'), ('four', 'five', 'six')]
>>> print "\n".join(map("\t".join,l))
one two three
four five six
>>>
【讨论】:
map 构建列表 -- 没必要。
open("data.txt", "w").write("\n".join(("\t".join(item)) for item in list))
【讨论】:
恕我直言,最惯用的方法是使用列表推导和连接:
print '\n'.join('\t'.join(i) for i in l)
【讨论】:
您不必提前加入列表:
with open("output.txt", "w") as fp:
fp.writelines('%s\n' % '\t'.join(items) for items in a_list)
【讨论】: