Print a nested list line by line - Python

后端 未结 7 1531
-上瘾入骨i
-上瘾入骨i 2020-12-15 12:51

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

相关标签:
7条回答
  • 2020-12-15 13:26

    print without trailing comma will print a newline character.

    for r in A:
        for t in r:
            print t,
        print
    
    0 讨论(0)
  • for r in A:
        print '%d %d %d' % tuple(r)
    
    0 讨论(0)
  • 2020-12-15 13:33
    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 if 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()
    
    0 讨论(0)
  • 2020-12-15 13:35

    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

    0 讨论(0)
  • 2020-12-15 13:37

    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.

    0 讨论(0)
  • 2020-12-15 13:39

    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.

    0 讨论(0)
提交回复
热议问题