考慮以下代碼:
array = np.array2string(np.arange(27).reshape(3,3,3))
這將創建一個具有 3D 維度的 numpy 陣列。輸出將如下所示:
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]
[[ 9 10 11]
[12 13 14]
[15 16 17]]
[[18 19 20]
[21 22 23]
[24 25 26]]]
我想將此 numpy 陣列轉換為 python 串列,其中每個索引對應于 numpy 陣列中的一行。重要的是要注意每個數字之間有一個空格。所以輸出看起來像這樣:
Index Type Size Value
0 str 5 0 1 2
1 str 5 3 4 5
2 str 5 6 7 8
3 str 5 9 10 11
....
.... and so on
我將如何編碼?
uj5u.com熱心網友回復:
您可以通過一系列替換來做到這一點:
my_array = np.array2string(np.arange(27).reshape(3,3,3))
# remove brackets
my_array = my_array.replace('[', '').replace(']', '').split('\n')
# remove space at the beginning of each line
my_array = [line.lstrip() for line in my_array]
# keep only strings that are not empty
my_array = [line for line in my_array if line]
結果:
['0 1 2',
'3 4 5',
'6 7 8',
'9 10 11',
'12 13 14',
'15 16 17',
'18 19 20',
'21 22 23',
'24 25 26']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/414372.html
標籤:
下一篇:如何計算陣列每行中點之間的距離
