python - 将字符串字典转换为可索引数组
问题描述
我有一个字符串字典(存储为数组),我想将它们转换回原来的类型。为什么?我正在读取和写入一个 json 文件,并且需要在从文件中读取它后将它们转换回数组。
"KdBP": "[13, 31]",
"KdV": "[0.001, 0.002]",
"KiBP": "[13, 31]",
"KiV": "[0.01, 0.02]",
"KpBP": "[13, 31]",
"KpV": "[0.175, 0.225]"
}
b = np.asarray(a["KdBP"])
print(b)```
=====
```[13, 31]```
As expected!
====
```print(b[0])```
```IndexError: too many indices for array```
What?!
====
```b = np.asarray(a["KdBP"])
print(b)
c = np.asarray(a["KdV"])
print(c)
d = b,c```
====
```[13, 31]
[0.001, 0.002]
(array('[13, 31]', dtype='<U8'), array('[0.001, 0.002]', dtype='<U14'))```
What the heck? What's this extra (array('... garbage?
All I'm trying to do is convert the string "[13.25, 31.21]" to an indexable array of floats --> [13.25, 31.21]
解决方案
np.asarray("[13, 31]")
返回一个 0 维数组,因此IndexError
. 同时,关于 额外的垃圾 数组,我认为您只是错过了print(d)
某个地方。
b = np.fromstring(a["KdBP"].strip(" []"), sep=",")
>>> print(b[0])
13.0
推荐阅读
- java - 将新的 xml 元素添加到现有元素
- php - 如何修复 laravel 5.7 中的“无效的日期时间格式:1366 不正确的整数值:”错误?
- html - Bootstrap 3 align-items-end 等价
- php - MySQLi 多表查询
- reactjs - History.Push 影响所有选项卡而不是当前选项卡
- unity3d - 如何优化 2D 游戏统一性(EarlyUpdate.PlayerCleanupCacheData)?
- amcharts - AM Charts - 以正确数据显示的折线图
- julia - 没有方法匹配错误,但识别匹配方法
- html - 在一行中使用完整的列高
- react-native - 如何使视图高度根据其兄弟姐妹的连续高度展开?