網站首頁 編程語言 正文
迭代數組
NumPy中引入了 nditer 對象來提供一種對于數組元素的訪問方式。
一、單數組迭代
1. 使用 nditer 訪問數組的每個元素
>>>a = np.arange(12).reshape(3, 4)
>>>for x in np.nditer(a):
?? ??? ??? ?print(x, end=' ')
0 1 2 3 4 5 6 7 8 9 10 11?
# 以上實例不是使用標準 C 或者 Fortran 順序,選擇的順序是和數組內存布局一致的,
# 這樣做是為了提升訪問的效率,默認是行序優先(row-major order,或者說是 C-order)。
# 這反映了默認情況下只需訪問每個元素,而無需考慮其特定順序。
# 我們可以通過迭代上述數組的轉置來看到這一點,
# 并與以 C 順序訪問數組轉置的 copy 方式做對比,如下實例:
>>>for x in np.nditer(a.T):
?? ??? ??? ?print(x, end=' ')
0 1 2 3 4 5 6 7 8 9 10 11?
>>>for x in np.nditer(a.T.copy(order='C')):
?? ??? ??? ?print(x, end=' ')
0 4 8 1 5 9 2 6 10 3 7 11?
2. 控制數組元素的迭代順序
使用參數 order 控制元素的訪問順序,參數的可選值有:
- ‘C’:C order,即是行序優先;
- ‘F’:Fortran order,即是列序優先;
- ’K’:參考數組元素在內存中的順序;
- ‘A’:表示’F’順序;
>>>a = np.arange(12).reshape(3, 4)
>>>for x in np.nditer(a, order='C'):
? ? ?? ?print(x, end=' ')
0 1 2 3 4 5 6 7 8 9 10 11?
>>>a = np.arange(12).reshape(3, 4)
>>>for x in np.nditer(a, order='F'):
? ? ?? ?print(x, end=' ')
0 4 8 1 5 9 2 6 10 3 7 11?
>>>a = np.arange(12).reshape(3, 4)
>>>for x in np.nditer(a, order='K'):
? ? ?? ?print(x, end=' ')
0 1 2 3 4 5 6 7 8 9 10 11?
>>>a = np.arange(12).reshape(3, 4)
>>>for x in np.nditer(a, order='A'):
? ? ?? ?print(x, end=' ')
0 1 2 3 4 5 6 7 8 9 10 11?
3. 修改數組值
在使用 nditer 對象迭代數組時,默認情況下是只讀狀態。因此,如果需要修改數組,可以使用參數 op_flags = 'readwrite' or 'writeonly' 來標志為讀寫或只讀模式。
此時,nditer 在迭代時將生成可寫的緩沖區數組,可以在此進行修改。為了在修改后,可以將修改的數據回寫到原始位置,需要在迭代結束后,拋出迭代結束信號,有兩種方式:
- 使用 with 上下文管理器;
- 在迭代結束后,調用迭代器的close方法;
>>>a = np.arange(12).reshape(3, 4)
>>>print(a)
>>>with np.nditer(a, op_flags=['readwrite']) as it:
for x in it:
x += 10
>>>print(a)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[10 11 12 13]
[14 15 16 17]
[18 19 20 21]]
4. 使用外部循環,跟蹤索引或多索引
以上操作在迭代過程中,都是逐元素進行的,這雖然簡單,但是效率不高。可以使用參數 flags 讓 nditer 迭代時提供更大的塊。并可以通過強制設定 C 和 F 順序,得到不同的塊大小。
# 默認情況下保持本機的內存順序,迭代器提供單一的一維數組
# 'external_loop' 給出的值是具有多個值的一維數組,而不是零維數組
>>>a = np.arange(12).reshape(3, 4)
>>>print(a)
>>>for x in np.nditer(a, flags=['external_loop']):
? ? ?? ?print(x, end=' ')
[[ 0 ?1 ?2 ?3]
?[ 4 ?5 ?6 ?7]
?[ 8 ?9 10 11]]
[ 0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 10 11],?
# 設定 'F' 順序
>>>a = np.arange(12).reshape(3, 4)
>>>print(a)
>>>for x in np.nditer(a, flags=['external_loop'], order='F'):
? ? ?? ?print(x, end=' ')
[[ 0 ?1 ?2 ?3]
?[ 4 ?5 ?6 ?7]
?[ 8 ?9 10 11]]
[0 4 8], [1 5 9], [ 2 ?6 10], [ 3 ?7 11],?
# 'c_index' 可以通過 it.index 跟蹤 'C‘ 順序的索引
>>>a = np.arange(12).reshape(3, 4)
>>>print(a)
>>>it = np.nditer(a, flags=['c_index'])
>>>for x in it:
? ??? ? ?? ?print("{}: ({})".format(x, it.index))
[[ 0 ?1 ?2 ?3]
?[ 4 ?5 ?6 ?7]
?[ 8 ?9 10 11]]
0: (0)
1: (1)
2: (2)
3: (3)
4: (4)
5: (5)
6: (6)
7: (7)
8: (8)
9: (9)
10: (10)
11: (11)
# 'f_index' 可以通過 it.index 跟蹤 'F‘ 順序的索引
>>>a = np.arange(12).reshape(3, 4)
>>>print(a)
>>>it = np.nditer(a, flags=['c_index'])
>>>for x in it:
? ??? ? ?? ?print("{}: ({})".format(x, it.index))
[[ 0 ?1 ?2 ?3]
?[ 4 ?5 ?6 ?7]
?[ 8 ?9 10 11]]
0: (0)
1: (3)
2: (6)
3: (9)
4: (1)
5: (4)
6: (7)
7: (10)
8: (2)
9: (5)
10: (8)
11: (11)
# 'multi_index' 可以通過 it.multi_index 跟蹤數組索引
>>>a = np.arange(12).reshape(3, 4)
>>>print(a)
>>>it = np.nditer(a, flags=['multi_index'])
>>>for x in it:
? ? ?? ?print("{}: {}".format(x, it.multi_index))
[[ 0 ?1 ?2 ?3]
?[ 4 ?5 ?6 ?7]
?[ 8 ?9 10 11]]
0: (0, 0)
1: (0, 1)
2: (0, 2)
3: (0, 3)
4: (1, 0)
5: (1, 1)
6: (1, 2)
7: (1, 3)
8: (2, 0)
9: (2, 1)
10: (2, 2)
11: (2, 3)
external_loop 與 multi_index、c_index、c_index不可同時使用,否則將引發錯誤 ValueError: Iterator flag EXTERNAL_LOOP cannot be used if an index or multi-index is being tracked
5. 以特定數據類型迭代
當需要以其它的數據類型來迭代數組時,有兩種方法:
- 臨時副本:迭代時,會使用新的數據類型創建數組的副本,然后在副本中完成迭代。但是,這種方法會消耗大量的內存空間。
- 緩沖模式: 使用緩沖來支持靈活輸入,內存開銷最小。
# 臨時副本
>>>a = np.arange(12).reshape(3, 4)
>>>print(a.dtype)
>>>it = np.nditer(a, op_flags=['readonly', 'copy'],op_dtypes=[np.float64])
>>>for x in it:
? ? ?? ?print("{}".format(x), end=', ')
int32
0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0,
# 緩沖模式
>>>a = np.arange(12).reshape(3, 4)
>>>print(a.dtype)
>>>it = np.nditer(a, flags=['buffered'],op_dtypes=[np.float64])
>>>for x in it:
? ? ?? ?print("{}".format(x), end=', ')
int32
0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0,?
注意
默認情況下,轉化會執行“安全”機制,如果不符合 NumPy 的轉換規則,會引發異常:TypeError: Iterator operand 0 dtype could not be cast from dtype('float64') to dtype('float32') according to the rule 'safe'
二、廣播數組迭代
如果不同形狀的數組是可廣播的,那么 dtype 可以迭代多個數組。
>>> a = np.arange(3)
>>> b = np.arange(6).reshape(2,3)
>>> for x, y in np.nditer([a,b]):
print("%d:%d" % (x,y), end=' ')
0:0 1:1 2:2 0:3 1:4 2:5
原文鏈接:https://blog.csdn.net/weixin_43276033/article/details/123767613
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2022-10-06 python中關于對super()函數疑問解惑_python
- 2022-05-22 利用DOSBox運行匯編的詳細步驟_匯編語言
- 2024-04-02 Centos無法獲取IP報No suitable device found for this con
- 2022-06-02 TensorFlow實現簡單線性回歸_python
- 2022-07-07 await context.Response.Body.WriteAsync("Hello from
- 2022-07-24 Git版本控制服務器詳解_其它綜合
- 2023-12-23 uni-app消息推送uni-push使用
- 2022-06-18 C語言詳細講解#error與#line如何使用_C 語言
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支