Python - Nested List to Tab Delimited File?

柔情痞子 提交于 2019-12-21 04:26:06

问题


I have a nested list comprising ~30,000 sub-lists, each with three entries, e.g.,

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.


回答1:


with open('fname', 'w') as file:
    file.writelines('\t'.join(i) + '\n' for i in nested_list)



回答2:


>>> nested_list = [['x', 'y', 'z'], ['a', 'b', 'c']]
>>> for line in nested_list:
...   print '\t'.join(line)
... 
x   y   z
a   b   c
>>> 



回答3:


In my view, it's a simple one-liner:

print '\n'.join(['\t'.join(l) for l in nested_list])



回答4:


>>> print '\n'.join(map('\t'.join,nested_list))
x       y       z
a       b       c
>>>



回答5:


out = file("yourfile", "w")
for line in nested_list:
    print >> out, "\t".join(line)


来源:https://stackoverflow.com/questions/2509706/python-nested-list-to-tab-delimited-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!