将字符串字典转换为可索引数组

时间:2019-05-06 21:58:04

标签: 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]

2 个答案:

答案 0 :(得分:1)

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

使用np.fromstring

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

>>> print(b[0])
13.0

答案 1 :(得分:1)

您要使用ast库进行此转换。查看this answer了解更多详细信息。

下面是我用来获取新字典的代码,其中键为字符串(不变),值为列表类型。

import ast
test_dict = {  "KdBP": "[13, 31]",
  "KdV": "[0.001, 0.002]",
  "KiBP": "[13, 31]",
  "KiV": "[0.01, 0.02]",
  "KpBP": "[13, 31]",
  "KpV": "[0.175, 0.225]"
}

for value in test_dict:
    print(type(test_dict[value]))
    converted_list = ast.literal_eval(test_dict[value])

    print(type(converted_list)) #convert string list to actual list
    new_dict = {value: converted_list}

    print(new_dict)

以下是输出:

enter image description here

您可以看到列表的字符串表示形式的类型变为实际列表。