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

发布于 2024-12-07 18:08:54 字数 702 浏览 1 评论 0原文

尽管我怀疑它有一个暂时从我的大脑中泄漏的简单修复程序,但在尝试实现以下目标时我感到有些悲伤。我需要能够打印一个可变尺寸的网格,该网格的左侧有数字,如下所示,

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

网格由嵌套列表组成,使用 enumeratei+1 像下面一样,

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

我可以在左侧得到这些数字,但是输出显示为列表,这是不整洁的,不完全是我想要的,目前我正在使用

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

Is There Something 打印网格(没有数字)否则我应该使用而不是枚举把这些数字放在一边?因为网格可以用可变参数设置,所以我真的希望有一种方法可以在打印它时实现这一点,而不是修改我用来构造网格的代码,我不顾一切地不去篡改至少它会破坏?我在互联网上进行了搜索,发现人们在他们绘制的任何图片的底部都有数字出现,而不是像这样出现在左侧。无论我将 enumerate 语句粘贴在 print_grid 函数中的哪个位置,它都会弄乱输出。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

献世佛 2024-12-14 18:08:54

您可以将每个列表连接成一个字符串:

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

You can join each list into a single string:

for i, line in enumerate(grid, 1):
    print i, ' '.join(line)
谈场末日恋爱 2024-12-14 18:08:54

您在找这个吗?

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

Are you looking for this?

for i, line in enumerate(grid):
   print i,
   for char in line:
      print char,
   print
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文