-2

I am looking to create a board in python with a 3x3 grid containing the values of 1-49.

Each numbers in the grid need to be able to be changed and replaced etc so the range function can't be used.

def board():

    board = [[1,2,3],
            [4,5,6],
            [7,8,9]]

    for i in board:
        print(i)

board()

The above code is all I have managed so far. The output displays a very amature-looking grid and it is not formatted nicely. Additionally, if I want to make the grid larger, say 7x7, the numbers do not line up properly.

The output displays the following:

[1, 2, 3]

[4, 5, 6]

[7, 8, 9]

How can I create and display a grid that looks neat with the numbers lining up in rows and columns with me being able to change the numbers in the grid.

idjaw
  • 25,487
  • 7
  • 64
  • 83
Tamir Cohen
  • 1
  • 1
  • 1
  • 1
  • 2
    Can you give an example of what your definition of "neat" is? It would help if you can provide a sample output of what the "ideal" scenario is. Furthermore, have you tried to take your code further to try to achieve the output it is you are trying to get to? – idjaw Jun 24 '17 at 01:19

3 Answers3

3

What do you mean by neat?

def board():

   board = [[1,2,3],
            [4,5,6],
            [7,8,9]]

   for i in board:
       for j in i:
         print(j, end = "  ")
       print()    

board()

This would print

  1  2  3  
  4  5  6  
  7  8  9  
Daniel Isaac
  • 745
  • 5
  • 15
0

Here is a one liner using list-comprehension:

print '\n'.join(' '.join(map(str, x)) for x in board)

output:

1 2 3
4 5 6
7 8 9
Mohd
  • 5,523
  • 7
  • 19
  • 30
0

Using Generator expression with join:

board = [[1,2,3],
         [4,15,6],
         [7,8,49]]

print('\n'.join('\t'.join('{:3}'.format(item) for item in row) for row in board))

Output:

    1     2     3
    4    15     6
    7     8    49
niraj
  • 17,498
  • 4
  • 33
  • 48