views:

233

answers:

5

Hi,

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.

+5  A: 
>>> nested_list = [['x', 'y', 'z'], ['a', 'b', 'c']]
>>> for line in nested_list:
...   print '\t'.join(line)
... 
x   y   z
a   b   c
>>> 
Eli Bendersky
Just curious would it help to store sublists as 3-tuples instead of lists? performance wise?
TheMachineCharmer
@TheMachineCharmer: Feel free to use `timeit` to see what the actual impact actually is. http://docs.python.org/library/timeit.html
S.Lott
@TheMachineCharmer: note that the real code probably doesn't have the lists hard-coded this way, but reads them from a file or gets them from another source
Eli Bendersky
+2  A: 
>>> print '\n'.join(map('\t'.join,nested_list))
x       y       z
a       b       c
>>>
S.Mark
+1  A: 
out = file("yourfile", "w")
for line in nested_list:
    print >> out, "\t".join(line)
fortran
+1  A: 
with open('fname', 'w') as file:
    file.writelines('\t'.join(i) + '\n' for i in nested_list)
SilentGhost
+2  A: 

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

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