gpt4 book ai didi

python - 如何在 YAML 文件中的 Python 中不带字符串打印 []

转载 作者:行者123 更新时间:2023-11-28 22:43:49 27 4
gpt4 key购买 nike

在我的 yam 文件中,我正在尝试这个

with open(fname, "w") as f:
yaml.safe_dump({'items':['test', 'test2']}, f,
default_flow_style=False, width=50, indent=4)

它以下面的格式打印

items:
- 'test'
- 'test2'

我希望输出格式如下

items: ['test', 'test2']

我该怎么做?

编辑:

这是我的完整代码

   d = {}        
for m in ['B1', 'B2', 'B3']:
d2 = {}
for f in ['A1', 'A2', 'A3']:
# here i don't want any flow style
d2[f] = ['test', 'test2']
d[m] = d2

with open(fname, "w") as f:
yaml.safe_dump(d, f, default_flow_style=True, width=50, indent=8)

最佳答案

然后不要放置 default_flow_style=Falsedoes the complete opposite of what you want :

>>> import yaml
>>> yaml.safe_dump({'items': ['test', 'test2']}, default_flow_style=False)
'items:\n- test\n- test2\n'
>>> yaml.safe_dump({'items': ['test', 'test2']})
'items: [test, test2]\n'

至于部分文档格式,你可以用自定义representers来做,例如:

class Items(list):
pass


def items_representer(dumper, data):
return dumper.represent_sequence('tag:yaml.org,2002:seq', data, flow_style=True)


yaml.representer.SafeRepresenter.add_representer(Items, items_representer)

result = yaml.safe_dump({
'items': Items(['test', 'test2']),
'other list': ['1', '2'],
}, default_flow_style=False)

# items: [test, test2]
# other list:
# - '1'
# - '2'
print(result)

关于python - 如何在 YAML 文件中的 Python 中不带字符串打印 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30159545/

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