在 Numpy 中创建数组,主对角线以下为 1,其他位置为 0


要创建数组,主对角线以下为 1,其他位置为 0,可以使用 Python Numpy 中的 numpy.tri() 方法。

  • 第一个参数是数组的行数。

  • 第二个参数是数组的列数。

  • 第三个参数 'k' 是数组填充的次对角线及其下方。

k = 0 是主对角线,而 k < 0 在其下方,k > 0 在其上方。默认为 0。tri() 函数返回一个数组,其下三角形填充为 1,其他位置为 0;换句话说,当 j <= i + k 时,T[i,j] == 1,否则为 0。

步骤

首先,导入所需的库 -

import numpy as np

现在,使用 numpy.tri() 方法创建数组,主对角线以下为 1,其他位置为 0 -

arr = np.tri(4, 4, k = -1)

显示数组 -

print("Array...
",arr)

获取数据类型 -

print("
Array datatype...
",arr.dtype)

获取数组的维度:-

print("
Array Dimensions...
",arr.ndim)

获取数组的形状 -

print("
Our Array Shape...
",arr.shape)

获取数组的元素数量 -

print("
Elements in the Array...
",arr.size)

示例

Open Compiler
import numpy as np # To create an array with ones below the main diagonal and zeros elsewhere, use the numpy.tri() method in Python Numpy # The 1st parameter is the number of rows in the array # The 2nd parameter is the number of columns in the array # The 3rd parameter 'k' is the sub-diagonal at and below which the array is filled. # The k = 0 is the main diagonal, while k < 0 is below it, and k > 0 is above. The default is 0. arr = np.tri(4, 4, k = -1) # Displaying our array print("Array...",arr) # Get the datatype print("Array datatype...",arr.dtype) # Get the dimensions of the Array print("Array Dimensions...",arr.ndim) # Get the shape of the Array print("Our Array Shape...",arr.shape) # Get the number of elements of the Array print("Elements in the Array...",arr.size)

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

Array...
[[0. 0. 0. 0.]
[1. 0. 0. 0.]
[1. 1. 0. 0.]
[1. 1. 1. 0.]]

Array datatype...
float64

Array Dimensions...
2

Our Array Shape...
(4, 4)

Elements in the Array...
16

更新于: 2022年2月10日

174 次查看

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告