Print a nested list line by line - Python

后端 未结 7 1548
-上瘾入骨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: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.

提交回复
热议问题