-1

I have a list like this:

grid_1 = ('  ##   ',
          ' ####  ',
          '####   ',
          '#######',
          ' ###   ',
          ' ##    ')

Where each element is the same length and consists of a space ' ' or a hash '#'

I would like to generate a new list where each element above is in its own sub-list, and each character is separated by a comma.

This is what I have so far:

workable_grid = [[None]*len(grid_1[0])] * len(grid_1)
for i in range(len(grid_1)):
    for j in range(len(grid_1[0])):
        workable_grid[i][j] = grid_1[i][j]

However the result I get is wrong:

wrong_list = [[' ', '#', '#', ' ', ' ', ' ', ' '],
              [' ', '#', '#', ' ', ' ', ' ', ' '],
              [' ', '#', '#', ' ', ' ', ' ', ' '],
              [' ', '#', '#', ' ', ' ', ' ', ' '],
              [' ', '#', '#', ' ', ' ', ' ', ' '],
              [' ', '#', '#', ' ', ' ', ' ', ' ']]

Any advice is appreciated. Thanks!

Martin
  • 41
  • 5

2 Answers2

3
good_grid = [ list(row) for row in grid_1 ]
Błotosmętek
  • 12,717
  • 19
  • 29
2

here is another version with even less code:

list(map(list, grid_1))

or

[*map(list, grid_1)]

the idea is to get your characters from each string in a separate list and hold all these lists in an outer list

output:

[[' ', ' ', '#', '#', ' ', ' ', ' '],
 [' ', '#', '#', '#', '#', ' ', ' '],
 ['#', '#', '#', '#', ' ', ' ', ' '],
 ['#', '#', '#', '#', '#', '#', '#'],
 [' ', '#', '#', '#', ' ', ' ', ' '],
 [' ', '#', '#', ' ', ' ', ' ', ' ']]
kederrac
  • 16,819
  • 6
  • 32
  • 55