4

If i had three lists such as

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]

And wanted to print it like this

1  4  7
2  5  8
3  6  9

How would i do that?

Outpost67
  • 41
  • 2
  • meaby duplicated http://stackoverflow.com/questions/13214809/pretty-print-2d-python-list, http://stackoverflow.com/questions/9712085/numpy-pretty-print-tabular-data, http://stackoverflow.com/questions/5909873/python-pretty-printing-ascii-tables – gustavodiazjaimes May 21 '13 at 19:28

3 Answers3

8

The hard part of this is transposing the array. But that's easy, with zip:

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
t = zip(a, b, c)

Now you just print it out:

print('\n'.join('  '.join(map(str, row)) for row in t))
abarnert
  • 354,177
  • 51
  • 601
  • 671
  • 2
    IMHO, a very readable solution. I like keeping the zip separate (unlike other answers) because transposing and displaying are fundamentally different things to do. – Thane Brimhall May 21 '13 at 19:31
6

This should do it:

'\n'.join(' '.join(map(str,tup)) for tup in zip(a,b,c))
mgilson
  • 300,191
  • 65
  • 633
  • 696
2

With list comprehension generator expression, without the map function:

'\n'.join(' '.join(str(y) for y in x) for x in zip(a,b,c))
pvoosten
  • 3,247
  • 27
  • 43
  • First, in cases where all you're doing is mapping a nicely-named function that you already have lying around, why not use `map`? Yeah, it's less readable when you have to build a `lambda` or a `partial`, but in this case, I think it's _more_ readable. (Also, you don't have a list comprehension here, you have a generator expression.) – abarnert May 21 '13 at 19:33
  • @abarnert: you just answered your question yourself: map unnecessarily creates a list, which is not created because I use a generator expression (sorry for the faulty naming, edited that). A generator is cleaner than a list. I should also use the functional equivalent of zip, so add `from itertools import izip as zip` to the top of the script. – pvoosten May 21 '13 at 19:44
  • @pvoosten: Actually, `join` creates a list when you give it an iterator (at least with CPython and PyPy, probably with all implementations). Also, `map` doesn't create a list in 3.x. Most importantly, the performance implications of creating a list of 3 elements are so negligible that even having this discussion is silly. Use whichever one is more readable. – abarnert May 21 '13 at 20:05