python - 将包含括号和数字的字符串转换为浮点数组
问题描述
如何将以下字符串转换为 numpy 浮点数组
'[[1.45757244e+03 0.00000000e+00 1.21294569e+03]
[0.00000000e+00 1.45752223e+03 1.00732059e+03]
[0.00000000e+00 0.00000000e+00 1.00000000e+00]]'
这是一种方法,但它很难拆分连续的“[”以使 cols 变量
def str2num(str_in, np_type, shape):
names_list = str_in.splitlines()
tem = []
for row in names_list:
is_str = isinstance(row, str)
if is_str:
cols = [s for s in row.split(string.whitespace+'[], ') if s]
for col in cols:
tem.append(col)
tem = flatten(tem)
return np.array(tem, dtype=np_type).reshape(shape)
解决方案
如果将字符串中的空格替换为逗号,则您将获得一个有效的 JSON 字符串,您可以使用以下命令读取该字符串json.loads
:
import json
import numpy as np
s = '''
[[1.45757244e+03 0.00000000e+00 1.21294569e+03]
[0.00000000e+00 1.45752223e+03 1.00732059e+03]
[0.00000000e+00 0.00000000e+00 1.00000000e+00]]
'''
a = np.array(json.loads(s.replace(' ', ',')), dtype=float)
print(a)
输出:
[[1.45757244e+03 0.00000000e+00 1.21294569e+03]
[0.00000000e+00 1.45752223e+03 1.00732059e+03]
[0.00000000e+00 0.00000000e+00 1.00000000e+00]]
推荐阅读
- python - numpy.fft2 结果是否产生遵循 numpy.fft 文档中描述的标准排序的结果?
- docker - Next.js 和 Docker 的问题 - Next 不获取文件中的更改
- memory - 虚拟机实例和我的个人计算机在并行代码上的内存使用/管理差异
- git - git push上的SSH“没有这样的文件或目录”错误
- github-actions - 如何表示 Github Action 依赖的版本范围
- javascript - 我的代码仅在打开 Web 开发工具时运行
- xamarin.forms - 将 Flyout Page 按钮的位置设置为底部
- icalendar - 如何从 caldav 数据库生成可订阅的 ics 链接
- sql-server - 是否有一种简单的(r)方法可以在 SQL Server 的一个表中的所有列中替换一个字符?
- python - 如何将 right_click_menu 与多个 InputText 元素一起使用?