如何将numpy数组的后续行与第一行对齐

发布于 2025-02-03 17:29:31 字数 812 浏览 2 评论 0原文

我将打印带有以下代码的结果。

import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print("a[[0,1,2]]:\n","\t",a[[0,1,2]])

但是只有第一行是缩进的,如以下结果所示:

a[[0,1,2]]:
         [[1 2 3]
 [4 5 6]
 [7 8 9]]

我希望输出显示如下:

a[[0,1,2]]:
          [[1 2 3]
           [4 5 6]
           [7 8 9]]

我可以使用以下代码来实现效果:

print("a[[0,1,2]]:")
count = 0
indentation = "\t "
for raw in a[[0,1,2]]:
    count += 1
    if count == 1:
        print(indentation,"[", end = "")
        print(raw)
    elif count <= len(a[[0,1,2]])-1:
        print(indentation,"",raw)
    elif count == len(a[[0,1,2]]):
        print(indentation,"",raw, end="")
        print("]")

但是我认为这不是显示显示的方便方法结果。有什么方法可以将整个数组直接移动到输出窗口中的右侧?

I indent the print result of numpy array with following codes.

import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print("a[[0,1,2]]:\n","\t",a[[0,1,2]])

But only the first row is indented, as shown in the following results :

a[[0,1,2]]:
         [[1 2 3]
 [4 5 6]
 [7 8 9]]

And I want the output to appear as follows :

a[[0,1,2]]:
          [[1 2 3]
           [4 5 6]
           [7 8 9]]

I could use the following code to realize the effect :

print("a[[0,1,2]]:")
count = 0
indentation = "\t "
for raw in a[[0,1,2]]:
    count += 1
    if count == 1:
        print(indentation,"[", end = "")
        print(raw)
    elif count <= len(a[[0,1,2]])-1:
        print(indentation,"",raw)
    elif count == len(a[[0,1,2]]):
        print(indentation,"",raw, end="")
        print("]")

But I don't think it is a convenient way to display the outcome. Is there any way to directly move the whole array to the right in the output window?

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

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

发布评论

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

评论(1

时光无声 2025-02-10 17:29:31

这是一个更简单,通用,填充功能:

def pad(a, sep='\t'):
    from itertools import repeat
    t = repeat(sep)
    return '\n'.join(map(''.join, zip(t, str(a).split('\n'))))

print("a[[0,1,2]]:\n", pad(a[[0,1,2]]))

输出:

a[[0,1,2]]:
    [[1 2 3]
     [4 5 6]
     [7 8 9]]

Here is a simpler, generic, padding function:

def pad(a, sep='\t'):
    from itertools import repeat
    t = repeat(sep)
    return '\n'.join(map(''.join, zip(t, str(a).split('\n'))))

print("a[[0,1,2]]:\n", pad(a[[0,1,2]]))

output:

a[[0,1,2]]:
    [[1 2 3]
     [4 5 6]
     [7 8 9]]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文