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

學(xué)無先后,達者為師

網(wǎng)站首頁 編程語言 正文

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

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

1. 二維(多維)數(shù)組降為一維數(shù)組

方法1: reshape()+concatenate 函數(shù),

這個方法是間接法,利用 reshape() 函數(shù)的屬性,間接的把二維數(shù)組轉(zhuǎn)換為一維數(shù)組;

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() 函數(shù),

推薦使用這個方法,這個方法是 numpy 自帶的函數(shù);

# coding = utf-8
import numpy as np
import random

# 把二維數(shù)組轉(zhuǎn)換為一維數(shù)組
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)

運行效果如下圖所示:

可以看到這兩種方式都可以把二維數(shù)組轉(zhuǎn)換為一維數(shù)組,但是推薦使用 flatten() 函數(shù),該方法也可以將多維數(shù)組轉(zhuǎn)換為一維數(shù)組。

import numpy as np
a = np.array([[1, 2], [3, 4], [9, 8]])
b = a.flatten()
print(b)

輸出結(jié)果為:[1, 2, 3, 4, 9, 8]

方法3: itertools.chain

import numpy as np
a = np.array([[1, 2], [3, 4], [9, 8]])

# 使用庫函數(shù)
from itertools import chain
a_a = list(chain.from_iterable(a))
print(a_a)

輸出結(jié)果為:[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:列表推導(dǎo)式

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. 一維數(shù)組升為 2 維數(shù)組

方法1:numpy 方法

利用函數(shù) reshape 或者是 resize

使用 reshape 的時候需要注意 reshape 的結(jié)果不改變,因此適用于還要用到原數(shù)組的情況。

使用 resize 會改變原數(shù)組,因此適用于一定需要修改后的結(jié)果為值的情況。

import numpy as np

x = np.arange(20)  # 生成數(shù)組
print(x)

result = x.reshape((4, 5))  # 將一維數(shù)組變成4行5列  原數(shù)組不會被修改或者覆蓋
x.resize((2, 10))  # 覆蓋原來的數(shù)據(jù)將新的結(jié)果給原來的數(shù)組
print(x)

輸出結(jié)果

[ 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]]

總結(jié)

原文鏈接:https://blog.csdn.net/weixin_46713695/article/details/126725305

欄目分類
最近更新