Question

I've come to some grief in trying to achieve the following though I suspect it has a simple fix that has temporarily leaked from my brain. I need to be able to to print a grid of variable dimensions that has numbers down the left-hand side like below

1 - + -
2 + - + 
3 - + -

the grid is composed in nested lists, using enumerate with i+1 like below

for i, line in enumerate(grid):
    return i+1, line

I can get those numbers on the left hand side however the output appears as lists which is untidy and not quite what I'm after, at the moment I'm printing the grid (with no numbers) using

def print_grid(grid):
    for line in grid:
        for char in line:
            print char,
        print

Is there something else that I ought to be using instead of enumerate to get those numbers along the side? Because the grid can be set up with variable parameters I was really hoping there would be a way of achieving this in printing it, rather than modifying the code I used to construct the grid which I'm desperate not to tamper with least it break? I've had a search around the internet and have found instances where people have had numbers appearing at the base of whatever picture they are drawing but not down the left hand side like that. No matter where I stick the enumerate statement in the print_grid function it messes up the output.

Was it helpful?

Solution

Are you looking for this?

for i, line in enumerate(grid):
   print i,
   for char in line:
      print char,
   print

OTHER TIPS

You can join each list into a single string:

for i, line in enumerate(grid, 1):
    print i, ' '.join(line)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top