由元素列表组成的 YAML 键 [英] YAML key consisting of a list of elements

查看:29
本文介绍了由元素列表组成的 YAML 键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有一个元素列表作为键,以便我可以检查是否满足多个条件.示例(不知道这是否可行,语法是否正确):

I need to have a list of elements as a key, so that I can check if several conditions are met. Example (don't know if this is possible and if the syntax is correct):

mapping:
  c_id:
    [pak, gb]: '4711'
    [pak, ch]: '4712'
    [pak]: '4713'
  d_id:
    .
    .
    .

现在我需要知道是否可以采用示例中的方法.

Now I need to know if it is possible to have an approach as in the example.

推荐答案

除了 Anthon 的回答之外,您还可以使用 PyYaml 进行以下操作:

In addition to Anthon's answer, here is how you can do it with PyYaml:

mapping:
  c_id:
    !!python/tuple [pak, gb]: '4711'
    !!python/tuple [pak, ch]: '4712'
    !!python/tuple [pak]: '4713'

诀窍是告诉 PyYaml 您想将键加载到元组中(因为列表不能用作字典键).没有办法隐式做到这一点,但这并不意味着这是不可能的.

The trick is to tell PyYaml that you want to load the keys into a tuple (since a list cannot be used as dict key). There is no way to do this implicitly, but this does not mean that it is not possible.

在这种情况下,显式键可能更具可读性:

Explicit keys may be more readable in this case:

mapping:
  c_id:
    ? !!python/tuple [pak, gb]
    : '4711'
    ? !!python/tuple [pak, ch]
    : '4712'
    ? !!python/tuple [pak]
    : '4713'

这个例子在语义上等同于第一个.

This example is semantically equivalent to the first one.

这篇关于由元素列表组成的 YAML 键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆