2010-02-22 73 views
0

我的Python模块有一个列表,其中包含我想要保存为某个.txt文件的所有数据。该列表包含多个元组,像这样:导出列表为.txt(Python)

list = [ ('one', 'two', 'three'), ('four', 'five', 'six')] 

如何打印列表,以便每个元组项目是由制表符分隔,并且每个元组由一个换行符分开?

感谢

回答

8
print '\n'.join('\t'.join(x) for x in L) 
+0

说'序列项目0:期望的字符串,找到的元组' – 3zzy 2010-02-22 04:58:19

+0

是。修正了。 – 2010-02-22 04:58:55

2

试试这个

"\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 
>>> 
+0

'map'构建列表 - 不必要的。 – 2010-03-19 23:30:00

2
open("data.txt", "w").write("\n".join(("\t".join(item)) for item in list)) 
+0

说'参数1必须是字符串或只读字符缓冲区,而不是发生器' – 3zzy 2010-02-22 04:59:11

+0

我纠正它,再试一次 – 2010-02-22 05:39:41

1

最习惯的方法,恕我直言,是用一个列表理解和联接:

print '\n'.join('\t'.join(i) for i in l) 
+0

我看到这里没有列表理解。 – 2010-03-19 23:29:11

9

你可以解决它,因为其他答案只是通过加入行来提示,但更好的方法是只使用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 
+0

感谢您的替代方法,但我太初学者尝试它:) – 3zzy 2010-02-22 05:09:40

+0

但方式,它更简单,因为你只是使用std库,但是对于初学者,你也必须知道如何去做:) – 2010-02-22 05:13:53

+1

好的解决方案不过,不要使用'list'作为变量名称。 – 2010-02-22 06:50:34

0

您不必参加提前名单:

with open("output.txt", "w") as fp: 
    fp.writelines('%s\n' % '\t'.join(items) for items in a_list)