【问题标题】:Return all lists and their contents from a YAML file从 YAML 文件中返回所有列表及其内容
【发布时间】:2020-12-11 19:10:33
【问题描述】:

我正在尝试为列表编写自定义 yaml lint 规则。但是,我无法弄清楚如何从文件中获取列表。

例如,如果我有以下文件:

变量1.yaml:

---
list1:
  - list1value1
  - list1value2
  - list1value3
string1: this_is_a_string
bool1: true
list2:
  - list2value1
  - list2value2
  - list2value3

variables2.yaml:

---
dict1:
  dict1list1:
    - dict1list1value1
    - dict1list1value2
  dict1bool1: false
bool2: true
list3:
  - list3value1
  - list3value2
  - list3value3
list4:
  - list4value1
  - list4value2

那么我想要的是:

>>> for name, values in get_lists_from_yaml_file("variable1.yaml"):
    print(name: values)

list1: ['list1value1', 'list1value2', 'list1value3']
list2: ['list2value1', 'list2value2', 'list2value3']

>>> for name, values in get_lists_from_yaml_file("variables2.yaml"):
    print(name: values)

dict1list1: ['dict1list1value1', 'dict1list1value2']
list3: ['list3value1', 'list3value2', 'list3value3']
list4: ['list4value1', 'list4value2']

额外的好处:声明列表的行号

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 请展示您编写的代码,因为 StackOverflow 不是代码编写服务,如果您不诚实地尝试,您可能会拒绝投票。

标签: python yaml pyyaml


【解决方案1】:

加载 yaml 后,我们就有了一个 python dict。我们遍历 dict 项并检查哪个值是列表。

试试下面的

import yaml

with open('variables1.yaml') as f:
    data = yaml.load(f, Loader=yaml.FullLoader)
    for k, v in data.items():
        if isinstance(v, list):
            print(f'{k} --> {v}')

输出

list1 --> ['list1value1', 'list1value2', 'list1value3']
list2 --> ['list2value1', 'list2value2', 'list2value3']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-11
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多