首页 > 解决方案 > 将字符串字典转换为可索引数组

问题描述

我有一个字符串字典(存储为数组),我想将它们转换回原来的类型。为什么?我正在读取和写入一个 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]

标签: python

解决方案


np.asarray("[13, 31]")返回一个 0 维数组,因此IndexError. 同时,关于 额外的垃圾 数组,我认为您只是错过了print(d)某个地方。

使用np.fromstring

b = np.fromstring(a["KdBP"].strip(" []"), sep=",")

>>> print(b[0])
13.0

推荐阅读