Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a nested list line by line - Python

A = [[1, 2, 3], [2, 3, 4], [4, 5, 6]]

I am trying my best to print A of the form:

1 2 3
2 3 4
4 5 6

That is in different lines, but I am unable to do so without all the elements in different lines. This is my code so far:

for r in A:
   for t in r:
       print(t,)
    print

This is my output:

1
2
3
2
3
4
4
5
6

It seems really simple, and I think a minor change would do it. Thanks!

like image 217
quarters Avatar asked May 29 '15 05:05

quarters


2 Answers

Use a simple for loop and " ".join() mapping each int in the nested list to a str with map().

Example:

>>> ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
>>> for xs in ys:
...     print(" ".join(map(str, xs)))
... 
1 2 3
4 5 6
7 8 9 10

The difference here is that we can support arbitrary lengths of inner lists.


The reason your example did not work as expected is because your inner loop is iterating over each element of the sub-list;

for r in A:  # r = [1, 2, 3]
    for t in r:  # t = 1 (on first iteration)
        print(t,)
    print

And print() by default prints new-line characters at the end unless you use: print(end="") I believe if you were using Python 2.x print t, would work. For example:

>>> ys = [[1, 2, 3], [4, 5, 6], [7, 8, 9, 10]]
>>> for xs in ys:
...     for x in xs:
...             print x,
...     print
... 
1 2 3
4 5 6
7 8 9 10

But print(x,) would not work as you intended it; Python 2.x or 3.x

like image 95
James Mills Avatar answered Oct 06 '22 12:10

James Mills


for r in A:
    print '%d %d %d' % tuple(r)
like image 34
dbliss Avatar answered Oct 06 '22 10:10

dbliss