網站首頁 編程語言 正文
1. 二維(多維)數組降為一維數組
方法1: reshape()+concatenate 函數,
這個方法是間接法,利用 reshape() 函數的屬性,間接的把二維數組轉換為一維數組;
import numpy as np mulArrays = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(list(np.concatenate(mulArrays.reshape((-1, 1), order="F")))) Out[1]: [1, 4, 7, 2, 5, 8, 3, 6, 9]
方法2: flatten() 函數,
推薦使用這個方法,這個方法是 numpy
自帶的函數;
# coding = utf-8 import numpy as np import random # 把二維數組轉換為一維數組 t1 = np.arange(12) print(t1) Out[0]: [ 0 1 2 3 4 5 6 7 8 9 10 11] t2 = t1.reshape(3, 4) print(t2) t3 = t2.reshape(t2.shape[0] * t2.shape[1], ) print(t3) t4 = t2.flatten() print(t4)
運行效果如下圖所示:
可以看到這兩種方式都可以把二維數組轉換為一維數組,但是推薦使用 flatten()
函數,該方法也可以將多維數組轉換為一維數組。
import numpy as np a = np.array([[1, 2], [3, 4], [9, 8]]) b = a.flatten() print(b)
輸出結果為:[1, 2, 3, 4, 9, 8]
方法3: itertools.chain
import numpy as np a = np.array([[1, 2], [3, 4], [9, 8]]) # 使用庫函數 from itertools import chain a_a = list(chain.from_iterable(a)) print(a_a)
輸出結果為:[1, 2, 3, 4, 9, 8]
方法4: sum()
mulArrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(sum(mulArrays, [])) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
方法5:operator.add + reduce
import operator from functools import reduce mulArrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(reduce(operator.add, mulArrays)) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
方法6:列表推導式
mulArrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print([i for arr in mulArrays for i in arr]) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
2. 一維數組升為 2 維數組
方法1:numpy 方法
利用函數 reshape
或者是 resize
。
使用 reshape
的時候需要注意 reshape
的結果不改變,因此適用于還要用到原數組的情況。
使用 resize
會改變原數組,因此適用于一定需要修改后的結果為值的情況。
import numpy as np x = np.arange(20) # 生成數組 print(x) result = x.reshape((4, 5)) # 將一維數組變成4行5列 原數組不會被修改或者覆蓋 x.resize((2, 10)) # 覆蓋原來的數據將新的結果給原來的數組 print(x)
輸出結果
[ 0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9 10 11 12 13 14 15 16 17 18 19]
[[ 0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9]
?[10 11 12 13 14 15 16 17 18 19]]
總結
原文鏈接:https://blog.csdn.net/weixin_46713695/article/details/126725305
相關推薦
- 2022-05-06 python畫圖時給圖中的點加標簽和plt.text的使用_python
- 2022-04-28 python實現簡單的學生成績管理系統_python
- 2022-11-21 初識React及React開發依賴詳解_React
- 2022-02-28 Chrome控制臺提示“Slow network is detected. Fallback fon
- 2022-11-15 python列表中常見的一些排序方法_python
- 2023-05-17 一文速學Python+Pyecharts繪制樹形圖_python
- 2022-08-29 Python基礎語法之變量與數據類型詳解_python
- 2022-07-15 SQL?Server數據表壓縮_MsSql
- 最近更新
-
- 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同步修改后的遠程分支