我有一个字符串的dict(存储为数组),我想把它们转换回原来的类型。为什么?我正在读写一个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-d数组,因此IndexError
。 然而,关于额外的垃圾数组,我认为您只是在某个地方遗漏了一个print(d)
使用^{} :
您想将ast库用于此转换。查看this answer了解更多详细信息
下面是我用来获取一个新字典的代码,其中键是字符串(未更改),值是列表类型
以下是输出:
您可以看到列表的字符串表示形式的类型变成了实际的列表
相关问题 更多 >
编程相关推荐