简体   繁体   English

使用python中的枚举在单独的行上打印编号的嵌套列表

[英]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 网格由嵌套列表组成,使用i+1 enumerate ,如下所示

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. 无论我将枚举语句放在print_grid函数中的哪个位置,它都会弄乱输出。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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