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

2024-09-28 03:24:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串的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]

Tags: theto字符串json类型np数组array
2条回答

np.asarray("[13, 31]")返回0-d数组,因此IndexError。 然而,关于额外的垃圾数组,我认为您只是在某个地方遗漏了一个print(d)

使用^{}

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

>>> print(b[0])
13.0

您想将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

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

相关问题 更多 >

    热门问题