python - 如何使用 PyYAML 读取 python 元组?

标签 python yaml pyyaml

我有以下名为 input.yaml 的 YAML 文件:

cities:
  1: [0,0]
  2: [4,0]
  3: [0,4]
  4: [4,4]
  5: [2,2]
  6: [6,2]
highways:
  - [1,2]
  - [1,3]
  - [1,5]
  - [2,4]
  - [3,4]
  - [5,4]
start: 1
end: 4

我正在使用 PyYAML 加载它并按如下方式打印结果:

import yaml

f = open("input.yaml", "r")
data = yaml.load(f)
f.close()

print(data)

结果是以下数据结构:

{ 'cities': { 1: [0, 0]
            , 2: [4, 0]
            , 3: [0, 4]
            , 4: [4, 4]
            , 5: [2, 2]
            , 6: [6, 2]
            }
, 'highways': [ [1, 2]
              , [1, 3]
              , [1, 5]
              , [2, 4]
              , [3, 4]
              , [5, 4]
              ]
, 'start': 1
, 'end': 4
}

如您所见,每个城市和高速公路都表示为一个列表。但是,我希望将它们表示为一个元组。因此,我使用理解手动将它们转换为元组:

import yaml

f = open("input.yaml", "r")
data = yaml.load(f)
f.close()

data["cities"] = {k: tuple(v) for k, v in data["cities"].items()}
data["highways"] = [tuple(v) for v in data["highways"]]

print(data)

但是,这似乎是一个 hack。有什么方法可以指示 PyYAML 直接将它们读取为元组而不是列表?

最佳答案

我不会因为您尝试做的事情而将您所做的事情称为 hacky。根据我的理解,您的替代方法是在 YAML 文件中使用特定于 python 的标签,以便在加载 yaml 文件时适本地表示它。但是,这需要您修改您的 yaml 文件,如果该文件很大,可能会非常烦人且不理想。

查看PyYaml doc这进一步说明了这一点。最终你想在你想要这样表示的结构前面放置一个 !!python/tuple 。要获取您的示例数据,它需要:

YAML 文件:

cities:
  1: !!python/tuple [0,0]
  2: !!python/tuple [4,0]
  3: !!python/tuple [0,4]
  4: !!python/tuple [4,4]
  5: !!python/tuple [2,2]
  6: !!python/tuple [6,2]
highways:
  - !!python/tuple [1,2]
  - !!python/tuple [1,3]
  - !!python/tuple [1,5]
  - !!python/tuple [2,4]
  - !!python/tuple [3,4]
  - !!python/tuple [5,4]
start: 1
end: 4

示例代码:

import yaml

with open('y.yaml') as f:
    d = yaml.load(f.read())

print(d)

输出:

{'cities': {1: (0, 0), 2: (4, 0), 3: (0, 4), 4: (4, 4), 5: (2, 2), 6: (6, 2)}, 'start': 1, 'end': 4, 'highways': [(1, 2), (1, 3), (1, 5), (2, 4), (3, 4), (5, 4)]}

关于python - 如何使用 PyYAML 读取 python 元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39553008/

相关文章:

php - 如何使用 PEAR 正确安装 PHPUnit?

validation - 本地验证travis.yml文件

python - 如何在Python中重置字典中的值?

python - 使用 Python 从网页中抓取表格

python - 如何将模型导入 django 项目中的 python 文件?

python - min python 的意外行为

python - 在给定列表中创建重复元素的新列表

ansible - Ansible list 可以包含另一个吗?

python - 如何使用 PyYAML 创建日期时间对象

python - 是否可以在 YAML 中锚定文字 block ?