Search code examples
pythonlistlist-comprehension

Combine elements of a list of lists into a string


I have to combine these 2 lists:

dots = [['.', '.', '.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.', '.', '.', '.', '.'],
 ['.', '.', '.', '.', '.', '.', '.', '.', '.']]
spaces = [['   ', '   ', '   ', '   ', '   ', '   ', '   ', '   ', '   '],
 ['   ', '   ', '   ', '   ', '   ', '   ', '   ', '   ', '   '],
 ['   ', '   ', '   ', '   ', '   ', '   ', '   ', '   ', '   '],
 ['   ', '   ', '   ', '   ', '   ', '   ', '   ', '   ', '   '],
 ['   ', '   ', '   ', '   ', '   ', '   ', '   ', '   ', '   '],
 ['   ', '   ', '   ', '   ', '   ', '   ', '   ', '   ', '   '],
 ['   ', '   ', '   ', '   ', '   ', '   ', '   ', '   ', '   '],
 ['   ', '   ', '   ', '   ', '   ', '   ', '   ', '   ', '   '],
 ['   ', '   ', '   ', '   ', '   ', '   ', '   ', '   ', '   ']]

I want every dot separeted by a space and turn them into string just like this:

.   .   .   .   .   .   .   .   .
.   .   .   .   .   .   .   .   .
.   .   .   .   .   .   .   .   .
.   .   .   .   .   .   .   .   .
.   .   .   .   .   .   .   .   .
.   .   .   .   .   .   .   .   .
.   .   .   .   .   .   .   .   .
.   .   .   .   .   .   .   .   .

I wrote this code but it only work for the first line:

lists = [a for b in zip(dots[0], spaces[0]) for a in b]
line = ''.join(liste)

I wanted to know how to loop in for every other sublist in these two lists.


Solution

  • You know how to use zip to simultaneously iterate over two lists, so do that and create a list of strings containing a dot and space for each "row":

    lines = [
              "".join(
                  dot + space 
                  for dot, space in zip(row_dots, row_spaces)
              )
              for row_dots, row_spaces in zip(dots, spaces) 
           ]
    

    Then join the individual lines using the newline character '\n'.

    output = "\n".join(lines)
    print(output)
    
    .   .   .   .   .   .   .   .   .
    .   .   .   .   .   .   .   .   .
    .   .   .   .   .   .   .   .   .
    .   .   .   .   .   .   .   .   .
    .   .   .   .   .   .   .   .   .
    .   .   .   .   .   .   .   .   .
    .   .   .   .   .   .   .   .   .
    .   .   .   .   .   .   .   .   .
    .   .   .   .   .   .   .   .   .
    

    Of course, you can combine both into a single statement so that you don't need to create the list of lines:

    output = "\n".join(
                  "".join(
                      dot + space 
                      for dot, space in zip(row_dots, row_spaces)
                  )
                  for row_dots, row_spaces in zip(dots, spaces) 
             )