tags:

views:

139

answers:

2

Hi. How do I do the following in Python 2.2 using built-in modules only?

I have a list of lists like this:
[['dog', 1], ['cat', 2, 'a'], ['rat', 3, 4], ['bat', 5]]

And from it I'd like to produce a string representation of a table like this where the columns are delimited by tabs and the rows by newlines.

dog 1
cat 2   a
rat 3   4
bat 5

i.e.
'dog\t1\ncat\t2\ta\nrat\t3\t4\nbat\t5'

+7  A: 

Like this, perhaps:

lists = [['dog', 1], ['cat', 2, 'a'], ['rat', 3, 4], ['bat', 5]]
result = "\n".join("\t".join(map(str,l)) for l in lists)

This joins all the inner lists using tabs, and concatenates the resulting list of strings using newlines.

It uses a feature called list comprehension to process the outer list.

Konrad Rudolph
You need to convert the ints to strings before you join them.
Dave
you'll have to make sure that each element in the 'lists' variable is a string, but other than that, the code snippet is extremely concise and expressive. I really should spend more time with Python....
Andrew Garrison
You can also change the second line to: result = '\n'.join('\t'.join(str(el) for el in list) for list in lists)
mipadi
@Dave, S.Lott: thanks – I completely forgot that …
Konrad Rudolph
Perfect. Thank you.
+4  A: 
# rows contains the list of lists
lines = []
for row in rows:
    lines.append('\t'.join(map(str, row)))
result = '\n'.join(lines)
Dave
+1 to keeping it simple and easily readable
nosklo