gpt4 book ai didi

python - 指定 PyYAML 转储部分的样式(二): sequences

转载 作者:太空宇宙 更新时间:2023-11-03 15:09:18 24 4
gpt4 key购买 nike

这是 Specifying styles for portions of a PyYAML dump 的后续问题:

考虑以下包含手动格式化 YAML 数据作为输入的代码。我正在修改 YAML 数据,但希望在写入的 YAML 文件中将边缘保留在单行上。

import yaml

st2 = yaml.load("""
edges:
- [1, 2]
- [2, 1, [1,0]]
""")
print yaml.dump(st2)

class blockseq( dict ): pass
def blockseq_rep(dumper, data):
return dumper.represent_mapping( u'tag:yaml.org,2002:seq', data, flow_style=False )

class flowmap( dict ): pass
def flowmap_rep(dumper, data):
return dumper.represent_mapping( u'tag:yaml.org,2002:map', data, flow_style=True )

class blockseqtrue( dict ): pass
def blockseqtrue_rep(dumper, data):
return dumper.represent_mapping( u'tag:yaml.org,2002:seq', data, flow_style=True )

yaml.add_representer(blockseq, blockseq_rep)
yaml.add_representer(blockseqtrue, blockseqtrue_rep)
yaml.add_representer(flowmap, flowmap_rep)

st2['edges'] = [ blockseqtrue(x) for x in st2['edges'] ]
print yaml.dump(st2)

此脚本退出并显示以下输出显示错误:

edges:
- [1, 2]
- - 2
- 1
- [1, 0]

Traceback (most recent call last):
File "test-yaml-rep.py", line 42, in <module>
st2['edges'] = [ blockseqtrue(x) for x in st2['edges'] ]
TypeError: cannot convert dictionary update sequence element #0 to a sequence

最佳答案

你的问题是我的两个类都对字典而不是列表进行操作。你想要一些可以与列表一起使用的东西:

class blockseqtrue( list ): pass
def blockseqtrue_rep(dumper, data):
return dumper.represent_sequence( u'tag:yaml.org,2002:seq', data, flow_style=True )

Python 列表是 YAML 序列/序列。 Python 字典是 YAML 映射/ map 。

关于python - 指定 PyYAML 转储部分的样式(二): sequences,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28974357/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com