在NumPy中使用不同輸出型別建立在給定對角線及其以下位置為1,其他位置為0的陣列
要建立一個在給定對角線及其以下位置為1,其他位置為0的陣列,請在Python NumPy中使用**numpy.tri()**方法。
- 第一個引數是陣列的行數。
- 第二個引數是陣列的列數。
- "type"引數用於設定返回陣列的型別。
tri()函式返回一個數組,其下三角形填充為1,其他位置為0;換句話說,當j <= i + k時,T[i,j] == 1,否則為0。
步驟
首先,匯入所需的庫:
import numpy as np
現在,使用numpy.tri()方法建立一個在給定對角線及其以下位置為1,其他位置為0的陣列:
arr = np.tri(3, 5, dtype = int)
顯示我們的陣列:
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 at and below the given 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 "type" parameter is used to set the type of the returned array
arr = np.tri(3, 5, dtype = int)
# 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... [[1 0 0 0 0] [1 1 0 0 0] [1 1 1 0 0]] Array datatype... int64 Array Dimensions... 2 Our Array Shape... (3, 5) Elements in the Array... 15
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP