是否可以在YAML中重用密钥而无需重新键入它们?如果可以通过锚点重复该键,则重命名该键很简单。
splitTestVariants:
lowCost: 0
mediumCost: 1
highCost: 2
pricePlans:
# reuse lowCost key instead this comment without retyping it
basic: 100
premium: 200
vip: 300
# reuse mediumCost key instead this comment without retyping it
basic: 200
premium: 300
vip: 400
# reuse highCost instead this comment without retyping it
basic: 300
premium: 400
vip: 500
答案 0 :(得分:0)
当然可以使用锚点和别名来减少键入:
import itertools as it
suffix = '.gz'
states = ([x, '![%c]' % x] for x in suffix)
for res in it.product(*states):
print ''.join(res)
给出:
import sys
import ruamel.yaml
yaml_str = """\
splitTestVariants:
&l lowCost: 0
&m mediumCost: 1
&h highCost: 2
pricePlans:
*l :
basic: 100
premium: 200
vip: 300
*m :
basic: 200
premium: 300
vip: 400
*h :
basic: 300
premium: 400
vip: 500
"""
yaml = ruamel.yaml.YAML()
yaml.default_flow_style = False
data = yaml.load(yaml_str)
print(list(data['pricePlans'].keys()))
以上是YAML的功能,而不是['lowCost', 'mediumCost', 'highCost']
(的
我是作者)。
请注意别名(ruamel.yaml
)和映射值指示符(*X
)之间的空格。并非所有YAML解析器(包括:
在指定`YAML(typ ='safe')时由libyaml
使用的C实现)都正确地解析了YAML锚和别名colons can be part of an anchor name,因此这里需要空格(或换行符)。