如何将numpy矩阵展平以进行打印

2024-05-19 03:05:50 发布

您现在位置:Python中文网/ 问答频道 /正文

为了更好地打印,我想将numpy矩阵展平:

我试过:

import numpy as np 
latt_const = 4.05
lattice = np.matrix([
    [1, 0, 0],
    [0, 1, 0],
    [0, 0, 1],
])
lattice_cmd = "custom {} a1 {} {} {} a2 {} {} {} a3 {} {} {}".format(
    latt_const, *lattice.flatten()
)

但这引发了一个例外:

IndexError: tuple index out of range

Tags: importnumpycmdformata2a1ascustom
2条回答

当您使用.format时,这个函数需要两个参数{}{},在您的例子中,这两个参数是latt\u const和晶格.展平(). 代码中的问题是不需要插入十个{},只需要其中两个。你知道吗

这应该起作用:

import numpy as np 
latt_const = 4.05
lattice = np.matrix([
    [1, 0, 0],
    [0, 1, 0],
    [0, 0, 1],
])
print("custom {} My_Matrix {} ".format(latt_const, lattice.flatten(0)))

或者,如果您需要将它们分开,请尝试:

import numpy as np
latt_const = 4.05
lattice = np.matrix([
  [1, 0, 0],
  [0, 1, 0],
  [0, 0, 1],
])
a1 = lattice[0,:]  # first row
a2 = lattice[1,:]  # second row
a3 = lattice[2,:]  # third row
print("custom {} a1 {} a2 {} a3 {} ".format(latt_const, a1, a2, a3))

使用np.array而不是np.matrix解决了这个问题。你知道吗

相关问题 更多 >

    热门问题