Print list of lists in separate lines

后端 未结 6 1852
生来不讨喜
生来不讨喜 2020-12-01 10:15

I have a list of lists:

a = [[1, 3, 4], [2, 5, 7]]

I want the output in the following format:

1 3 4
2 5 7
<
相关标签:
6条回答
  • 2020-12-01 10:20
    a = [[1, 3, 4], [2, 5, 7]]
    for i in a:
        for j in i:
            print(j, end = ' ')
        print('',sep='\n')
    

    output:

    1 3 4
    2 5 7
    
    0 讨论(0)
  • 2020-12-01 10:24

    You can do this:

    >>> lst = [[1, 3, 4], [2, 5, 7]]
    >>> for sublst in lst:
    ...     for item in sublst:
    ...             print item,        # note the ending ','
    ...     print                      # print a newline
    ... 
    1 3 4
    2 5 7
    
    0 讨论(0)
  • 2020-12-01 10:40

    oneliner:

    print('\n'.join(' '.join(map(str,sl)) for sl in l))
    

    explanation:
    you can convert list into str by using join function:

    l = ['1','2','3']
    ' '.join(l) # will give you a next string: '1 2 3'
    '.'.join(l) # and it will give you '1.2.3'
    

    so, if you want linebreaks you should use new line symbol.
    But join accepts only list of strings. For converting list of things to list of strings, you can apply str function for each item in list:

    l = [1,2,3]
    ' '.join(map(str, l)) # will return string '1 2 3'
    

    And we apply this construction for each sublist sl in list l

    0 讨论(0)
  • 2020-12-01 10:44

    Iterate through every sub-list in your original list and unpack it in the print call with *:

    a = [[1, 3, 4], [2, 5, 7]]
    for s in a:
        print(*s)
    

    The separation is by default set to ' ' so there's no need to explicitly provide it. This prints:

    1 3 4
    2 5 7
    

    In your approach you were iterating for every element in every sub-list and printing that individually. By using print(*s) you unpack the list inside the print call, this essentially translates to:

    print(1, 3, 4)  # for s = [1, 2, 3]
    print(2, 5, 7)  # for s = [2, 5, 7]
    
    0 讨论(0)
  • 2020-12-01 10:45

    I believe this is pretty simple:

    a = [[1, 3, 4], [2, 5, 7]]   # defines the list
    
    for i in range(len(a)):      # runs for every "sub-list" in a
        for j in a[i]:           # gives j the value of each item in a[i]
            print(j, end=" ")    # prints j without going to a new line
        print()                  # creates a new line after each list-in-list prints
    
    0 讨论(0)
  • 2020-12-01 10:45
    def print_list(s):
        for i in range(len(s)):
            if isinstance(s[i],list):
                k=s[i]
                print_list(k)
            else:
                print(s[i])
    
    s=[[1,2,[3,4,[5,6]],7,8]]
    print_list(s)
    

    you could enter lists within lists within lists ..... and yet everything will be printed as u expect it to be.

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