使用函式遍歷 NumPy 中的每個座標構建陣列
要透過執行函式遍歷每個座標來構建陣列,請在 Python NumPy 中使用 **numpy.fromfunction()** 方法。該函式使用 N 個引數呼叫,其中 N 是形狀的秩。每個引數表示沿特定軸變化的陣列的座標。例如,如果形狀為 (2, 2),則引數將為 array([[0, 0], [1, 1]]) 和 array([[0, 1], [0, 1]])
fromfunction() 返回對函式的呼叫的結果,並直接將其傳遞迴。因此,fromfunction 的形狀完全由函式決定。如果函式返回標量值,則 fromfunction 的形狀將與 shape 引數不匹配。
步驟
首先,匯入所需的庫 -
import numpy as np
要透過執行函式遍歷每個座標來構建陣列,請在 Python NumPy 中使用 numpy.fromfunction() 方法 -
print("Result
",np.fromfunction(lambda a, b: a, (3, 3), dtype=float))
print("
Result
",np.fromfunction(lambda a, b: b, (3, 3), dtype=float))檢查陣列元素是否相等 -
print("
Result
",np.fromfunction(lambda a, b: a == b, (4, 4), dtype=int))
新增元素 -
print("
Result
",np.fromfunction(lambda a, b: a + b, (5, 5), dtype=int))使用大於進行檢查 -
print("
Result
",np.fromfunction(lambda a, b: a > b, (5, 5), dtype=int))
使用小於進行檢查 -
print("
Result
",np.fromfunction(lambda a, b: a < b, (5, 5), dtype=int))示例
import numpy as np
# To construct an array by executing a function over each coordinate, use the numpy.fromfunction() method in Python Numpy
print("Result
",np.fromfunction(lambda a, b: a, (3, 3), dtype=float))
print("
Result
",np.fromfunction(lambda a, b: b, (3, 3), dtype=float))
# Checking for array elements equality
print("
Result
",np.fromfunction(lambda a, b: a == b, (4, 4), dtype=int))
# Adding elements
print("
Result
",np.fromfunction(lambda a, b: a + b, (5, 5), dtype=int))
# Checking with greater than
print("
Result
",np.fromfunction(lambda a, b: a > b, (5, 5), dtype=int))
# Checking with less than
print("
Result
",np.fromfunction(lambda a, b: a < b, (5, 5), dtype=int))輸出
Result [[0. 0. 0.] [1. 1. 1.] [2. 2. 2.]] Result [[0. 1. 2.] [0. 1. 2.] [0. 1. 2.]] Result [[ True False False False] [False True False False] [False False True False] [False False False True]] Result [[0 1 2 3 4] [1 2 3 4 5] [2 3 4 5 6] [3 4 5 6 7] [4 5 6 7 8]] Result [[False False False False False] [ True False False False False] [ True True False False False] [ True True True False False] [ True True True True False]] Result [[False True True True True] [False False True True True] [False False False True True] [False False False False True] [False False False False False]]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP