首页 > 解决方案 > 使用 .txt 中的 numpy 读取 4D 数组

问题描述

我生成了一个包含在 .txt 文件中的 4D 数组,如下所示:

[ [ [ [2.47, 1.57], [2.23, 5.95], [0.06, 2.54] ],

[ [0.79, 0.14], [1.64, 2.17], [0.86, 3.53] ],

[ [0.44, 3.42], [1.64, 5.39], [1.57, 2.63] ] ],


[ [ [2.34, 1.57], [0.75, 2.01], [2.86, 1.04] ],

[ [0.77, 1.25], [2.25, 6.08], [2.42, 0.51] ],

[ [1.44, 1.62], [2.44, 3.67], [2.99, 2.75] ] ],


[ [ [1.01, 3.35], [0.81, 0.29], [1.59, 4.37] ],

[ [0.29, 5.70], [0.10, 0.96], [3.08, 3.90] ],

[ [0.94, 2.27], [1.51, 1.87], [0.90, 5.81] ] ] ]

它是这样格式化的,因为我很容易像这样创建它。但是,由于括号,我无法设法使用 numpy.loadtxt() 将其正确加载为 python 中的正确 4D 数组。怎么做到呢?

标签: pythonarraysnumpynumpy-ndarray

解决方案


您可以使用ast将字符串作为 numpy 数组的变量读取,并使用 pathlib 将整个文件内容作为字符串读取,然后在一行中关闭文件,同样:

import numpy as np
import ast
from pathlib import Path

arr_str = Path('./text.txt').read_text()
arr = np.array(ast.literal_eval(arr_str))

推荐阅读