简体   繁体   中英

Printing numbered nested lists on separate lines using enumerate in python

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.

You can join each list into a single string:

for i, line in enumerate(grid, 1):
    print i, ' '.join(line)

Are you looking for this?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM