一、nditer的簡介
在numpy模塊中有一個非常有用的函數——np.nditer(),用於在多維數組中迭代元素。np.nditer()對象可以訪問數組的每個元素,可以指定迭代順序、迭代方式、以及每次迭代時所訪問的塊的大小。使用np.nditer()可以大大提高在多維數組上進行迭代時的效率。
二、np.nditer對象的創建與使用
定義一個np.nditer對象格式如下:
import numpy as np a = np.array([[1,2], [3,4]]) it = np.nditer(a) for x in it: print(x)
結果輸出:
1 2 3 4
以上代碼中,定義了一個二維數組a,然後使用np.nditer()函數創建了一個可迭代的對象it。通過for循環遍歷it迭代器中的每個元素並打印出來。
三、指定迭代順序
在默認情況下,np.nditer()函數使用“C風格”的迭代順序。但是,我們也可以使用其他的順序,比如“F風格”或者“多索引”方式。下面分別通過示例說明這三種迭代方式。
1.“C風格”迭代順序
“C風格”迭代順序是指以行為主序,以列為次序對數組進行遍歷。示例代碼如下:
import numpy as np a = np.array([[1,2], [3,4]]) it = np.nditer(a, flags=['multi_index'], order='C') while not it.finished: print("%d %s" % (it[0], it.multi_index)) it.iternext()
其中,order=’C’表示按“C風格”進行迭代,flags=[‘multi_index’]則表示迭代的同時輸出所迭代元素的下標。結果輸出如下:
1 (0, 0) 2 (0, 1) 3 (1, 0) 4 (1, 1)
2.“F風格”迭代順序
“F風格”迭代順序是指以列為主序,以行為次序對數組進行遍歷。示例代碼如下:
import numpy as np a = np.array([[1,2], [3,4]]) it = np.nditer(a, flags=['multi_index'], order='F') while not it.finished: print("%d %s" % (it[0], it.multi_index)) it.iternext()
輸出結果如下:
1 (0, 0) 3 (1, 0) 2 (0, 1) 4 (1, 1)
3.“多索引”方式迭代
“多索引”方式迭代是指可以同時遍歷多個數組。示例代碼如下:
import numpy as np a = np.array([[1,2], [3,4]]) b = np.array([[5,6], [7,8]]) it = np.nditer([a, b], flags=['multi_index'], order='C') while not it.finished: print("%d %s" % (it[0], it.multi_index)) it.iternext()
輸出結果如下:
1 (0, 0) 5 (0, 0) 2 (0, 1) 6 (0, 1) 3 (1, 0) 7 (1, 0) 4 (1, 1) 8 (1, 1)
四、指定塊大小
我們可以使用np.nditer()函數的“flags”參數來指定每次迭代時的塊大小,從而實現對大型數組的高效迭代。示例代碼如下:
import numpy as np a = np.arange(24).reshape(2,3,4) # 迭代時每次訪問2個元素(2表示塊大小) it = np.nditer(a, flags=['multi_index'], order='C', op_flags=['readwrite'], op_flags=['external_loop']) with it: for x in it: print(x, it.multi_index)
輸出結果如下:
0 (0, 0, 0) 1 (0, 0, 1) 2 (0, 0, 2) 3 (0, 0, 3) 4 (0, 1, 0) 5 (0, 1, 1) 6 (0, 1, 2) 7 (0, 1, 3) 8 (0, 2, 0) 9 (0, 2, 1) 10 (0, 2, 2) 11 (0, 2, 3) 12 (1, 0, 0) 13 (1, 0, 1) 14 (1, 0, 2) 15 (1, 0, 3) 16 (1, 1, 0) 17 (1, 1, 1) 18 (1, 1, 2) 19 (1, 1, 3) 20 (1, 2, 0) 21 (1, 2, 1) 22 (1, 2, 2) 23 (1, 2, 3)
五、總結
本文介紹了使用np.nditer()函數進行多維數組迭代的方法和使用場景。通過指定不同的迭代順序、迭代方式,以及設置合適的塊大小,可以大大提高在多維數組上進行迭代時的效率。np.nditer()函數在處理多維數組時非常有用,掌握其用法和技巧,可以幫助我們更高效地進行向量化的運算。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/243629.html