【问题标题】:Query yaml file with python用python查询yaml文件
【发布时间】:2021-02-25 10:04:09
【问题描述】:

我有一个由 py​​qtgraph 库生成的 yaml 文件,用于排列码头,如下所示:

float: []
main: !!python/tuple
- vertical
- - !!python/tuple
    - vertical
    - - !!python/tuple
        - horizontal
        - - !!python/tuple
            - dock
            - NameOfDock1
            - true
          - !!python/tuple
            - dock
            - NameOfDock2
            - true
          - !!python/tuple
            - dock
            - NameOfDock3
            - true
          - !!python/tuple
            - dock
            - NameOfDock4
            - true
          - !!python/tuple
            - dock
            - NameOfDock5
            - true
        - sizes:
          - 174
          - 174
          - 433
          - 388
          - 401
      - !!python/tuple
        - horizontal
        - - !!python/tuple
            - dock
            - NameOfDock6
            - true
          - !!python/tuple
            - dock
            - NameOfDock7
            - true
        - sizes:
          - 397
          - 1185
    - sizes:
      - 313
      - 93
  - !!python/tuple
    - horizontal
    - - !!python/tuple
        - dock
        - NameOfDock8
        - true
      - !!python/tuple
        - dock
        - NameOfDock9
        - true
    - sizes:
      - 791
      - 791
  - !!python/tuple
    - horizontal
    - - !!python/tuple
        - dock
        - NameOfDock10
        - true
      - !!python/tuple
        - dock
        - NameOfDock11
        - true
    - sizes:
      - 1318
      - 264
- sizes:
  - 410
  - 80
  - 80

有没有一种优雅的方式来查询这种 yaml 文件以获取所有码头名称的列表 ([NameOfDock1, NameOfDock2, NameOfDock3, NameOfDock4, ...])。我听说过 yaql 库,但如果可能的话,我更喜欢内置解决方案,但如果易于实施,我也欢迎它。提前感谢您的建议!

PS: 我认为有这样的查询会很优雅:如果在每个 python 元组中都存在“dock”元素而不是将下一个元素附加到dock_list,但我不确定如何实现它。

【问题讨论】:

    标签: python yaml pyyaml


    【解决方案1】:

    您的结构似乎是节点,其中每个节点要么是vertical,要么是horizontal,要么是dock。前两个有孩子作为第二个项目,dock 有一个名字。因此,获取所有码头名称的最简单方法是折叠:

    # get_docks returns a list of dock names in the given node
    def get_docks(data):
      # if it's a dock node, return a list with the dock's name as single item
      return [ data[1] ] if data[0] == "dock" else [
          dock for item in data[1] for dock in get_docks(item) ]
      # if not, call get_docks on each list item in the node's children and
      # accumulate the dock names in a single list
    
    print(get_docks(config))
    

    这会给你

    ['NameOfDock1', 'NameOfDock2', 'NameOfDock3', 'NameOfDock4', 'NameOfDock5', 'NameOfDock6', 'NameOfDock7', 'NameOfDock8', 'NameOfDock9', 'NameOfDock10', 'NameOfDock11']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-04
      • 2015-06-13
      • 1970-01-01
      • 2021-07-07
      • 2021-02-03
      • 2015-01-31
      • 2023-02-21
      相关资源
      最近更新 更多