Python - 用于制表符分隔文件的嵌套列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2509706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - Nested List to Tab Delimited File?
提问by Darren J. Fitzpatrick
I have a nested list comprising ~30,000 sub-lists, each with three entries, e.g.,
我有一个包含 ~30,000 个子列表的嵌套列表,每个子列表都有三个条目,例如,
nested_list = [['x', 'y', 'z'], ['a', 'b', 'c']].
I wish to create a function in order to output this data construct into a tab delimited format, e.g.,
我希望创建一个函数,以便将此数据构造输出为制表符分隔的格式,例如,
x y z
a b c
Any help greatly appreciated!
非常感谢任何帮助!
Thanks in advance, Seafoid.
提前致谢,海鱼。
采纳答案by SilentGhost
with open('fname', 'w') as file:
file.writelines('\t'.join(i) + '\n' for i in nested_list)
回答by Eli Bendersky
>>> nested_list = [['x', 'y', 'z'], ['a', 'b', 'c']]
>>> for line in nested_list:
... print '\t'.join(line)
...
x y z
a b c
>>>
回答by mojbro
In my view, it's a simple one-liner:
在我看来,这是一个简单的单行:
print '\n'.join(['\t'.join(l) for l in nested_list])
回答by YOU
>>> print '\n'.join(map('\t'.join,nested_list))
x y z
a b c
>>>
回答by fortran
out = file("yourfile", "w")
for line in nested_list:
print >> out, "\t".join(line)