在 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)示例
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)輸出
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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP