python - 使用 .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 数组。怎么做到呢?
解决方案
您可以使用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))
推荐阅读
- elasticsearch - Kibana 在 ElasticSearch 的搜索/发现中不显示来自冻结索引的数据
- mercurial - 在 tortoisehg 中推送到远程的 mercurial 提交的秘密阶段
- tensorflow - 运行 CNN-LSTM 模型时出错:ValueError:lstm_13 层的输入 0 与该层不兼容:预期 ndim=3
- python-3.x - 通过列表和其他按日期在 Dataframe 上添加多种排序
- time-complexity - CTCI 书中递归算法的空间复杂度
- corda - 我在运行corda节点时收到列“identity_value”是字节错误类型
- spring-boot - Spring Security 使用自定义登录页面拒绝访问
- ios - Objective C 如何使用 iBeacon 找出室内两部 iPhone 之间的距离
- python - Python2 与 Python3 浮点表示
- css - 自定义 Bootstrap 网格行和列