Print a nested list line by line - Python

孤街醉人 提交于 2019-11-29 02:34:06

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

for r in A:
    print '%d %d %d' % tuple(r)

Method-1 :

We can use list comprehension and .join() operator.

>>> my_list = [[1, 2, 3], [2, 3, 4], [4, 5, 6]]

>>> for item in my_list:
        print ' '.join(str(x) for x in item)

1 2 3
2 3 4
4 5 6

Method-2 :

>>> my_list = [[1, 2, 3], [2, 3, 4], [4, 5, 6]]

>>> for item in my_list:
        for x in item:
            print x,
        print 

1 2 3
2 3 4
4 5 6

Inner print with a comma ensures that inner list's elements are printed in a single line. Outer print ensures that for the next inner list, it prints in next line.

print without trailing comma will print a newline character.

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

The same question was answered by Jim Fasarakis Hilliard in Print list of lists in separate lines.

In Python 3.x we can use:

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

for i in A:
        print(*i)

And the corresponding output is:

1 2 3
2 3 4
4 5 6

If you are in Python 3.x:

print(*('{} {} {}'.format(*r) for r in A), sep='\n')

or:

print(*('%d %d %d' % tuple(r) for r in A), sep='\n')

If not, you can import Python 3.x's print function from the __future__ module.

for [a,b,c] in A:
   print(a,b,c)

This might help. But if you have more number of elements in the lists or elements in the nested lists are variable,This won't work. Below code will print all elements in a nested line in single line.

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