【发布时间】:2019-06-13 00:07:06
【问题描述】:
我在 YAML 中有一个配置文件,其中包含字符串、浮点数、整数和列表。我想,当 YAML 被加载时返回列表一个 numpy 数组。因此,例如,如果 YAML 如下:
name: 'John Doe'
age: 20
score:
-- 19
- 45
-- 21
- 12
-- 32
- 13
我读了这篇文章
import yaml
def read(CONFIG_FILE):
with open(CONFIG_FILE) as c:
return yaml.load(c)
config = read('path\to\yml')
然后我希望将config['score'] 而非列表键入为numpy.array。当然,这可以在 YAML 之外通过 numpy.array(config['score']) 之类的方式轻松完成,但我想避免这种情况。
我已尝试按照文档 (https://pyyaml.org/wiki/PyYAMLDocumentation) 中的说明设置标签,但无法使其正常工作。因此,例如,以下失败:
score:!!python/object:numpy.array
-- 19
- 45
-- 21
- 12
-- 32
- 13
将标签更改为!!python/module:numpy.array 或!!python/name:numpy.array 也不起作用。
我怎样才能做到这一点?我正在使用 Python v.3
【问题讨论】:
-
没有列表(即 YAML 中的序列),因为在开始
score的值的破折号后没有空格,这不是序列条目指示符,其余的是一个普通的多行标量。
标签: python arrays python-3.x yaml