0

I would like to be able to create a square list like this:

#[[   ],[   ],[   ]
# [   ],[   ],[   ]
# [   ],[   ],[   ]]

Using this code:

GRID_SIZE = 3
def placeMines():
    L = []
    for x in range(GRID_SIZE):
        for y in range(GRID_SIZE):
            L.append([])
    print(L)

However, I want to be able to make it so that the list goes over to the next row when it reaches the rows number(3 in this case) of lists. Kind of like a \nfor strings.

martineau
  • 99,260
  • 22
  • 139
  • 249
Lamar
  • 205
  • 2
  • 9

3 Answers3

1

you can use:

s = '[' + '\n '.join(','.join(['[   ]'] * GRID_SIZE)  for _ in range(GRID_SIZE)) + ']'
print(s)

output:

[[   ],[   ],[   ]
 [   ],[   ],[   ]
 [   ],[   ],[   ]]
kederrac
  • 15,339
  • 4
  • 25
  • 45
1

Since kederrac's answer was too literal on the comparison of the question with a string, I describe here the list data structure creation.

Both your visual example and code describe a (9,1) list, which I guess is not what you want. By your description I believe you are in need of one of the following objects.

A (3,3,1) list like this if the brackets in your visual example really represent other lists:

#[[[],[],[]],
# [[],[],[]],
# [[],[],[]]].

Or a (3,3) list like this if your brackets are not really lists but the values each position will assume:

#[[0, 0, 0],
# [0, 0, 0],
# [0, 0, 0]].

For both cases you can use nested list comprehensions, as follows:

For the first case:

L = [[[] for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]

For the second case:

L = [[0 for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]
1

You can do it by using the built-in divmod() function to do a little math like the following:

from pprint import pprint

GRID_SIZE = 3

def placeMines():
    L = []
    for i in range(GRID_SIZE**2):
        r, c = divmod(i, GRID_SIZE)
        if c == 0:  # New row?
            L.append([])
        L[-1].append(['   '])
    pprint(L)

placeMines()

Output:

[[['   '], ['   '], ['   ']],
 [['   '], ['   '], ['   ']],
 [['   '], ['   '], ['   ']]]
martineau
  • 99,260
  • 22
  • 139
  • 249