日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python將二維數組升為一維數組或二維降為一維方法實例_python

作者:趙孝正 ? 更新時間: 2022-12-15 編程語言

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

欄目分類
最近更新