可以使用numpy庫中的reshape函數(shù)將一維數(shù)組轉(zhuǎn)換為二維數(shù)組。假設(shè)一維數(shù)組名為arr,需要轉(zhuǎn)換為m行n列的二維數(shù)組,則可以使用如下代碼:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
m = 3 # 行數(shù)
n = 3 # 列數(shù)
arr_2d = np.reshape(arr, (m, n))
print(arr_2d)
輸出結(jié)果為:
[[1 2 3]
[4 5 6]
[7 8 9]]
也可以使用列表推導(dǎo)式來實(shí)現(xiàn)一維數(shù)組轉(zhuǎn)二維數(shù)組的功能,如下所示:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
m = 3 # 行數(shù)
n = 3 # 列數(shù)
arr_2d = [arr[i:i+n] for i in range(0, len(arr), n)]
print(arr_2d)
輸出結(jié)果為:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]