Lamar
Lamar

Reputation: 217

How to create a 2d list of rows and columns?

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.

Upvotes: 0

Views: 299

Answers (3)

martineau
martineau

Reputation: 123473

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:

[[['   '], ['   '], ['   ']],
 [['   '], ['   '], ['   ']],
 [['   '], ['   '], ['   ']]]

Upvotes: 1

Victor O. Costa
Victor O. Costa

Reputation: 15

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)]

Upvotes: 1

kederrac
kederrac

Reputation: 17322

you can use:

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

output:

[[   ],[   ],[   ]
 [   ],[   ],[   ]
 [   ],[   ],[   ]]

Upvotes: 1

Related Questions