gpt4 book ai didi

python yaml.dump 缩进错误

转载 作者:IT老高 更新时间:2023-10-28 20:53:31 28 4
gpt4 key购买 nike

我正在执行以下 python 代码:

import yaml


foo = {
'name': 'foo',
'my_list': [{'foo': 'test', 'bar': 'test2'}, {'foo': 'test3', 'bar': 'test4'}],
'hello': 'world'
}

print(yaml.dump(foo, default_flow_style=False))

但正在打印:

hello: world
my_list:
- bar: test2
foo: test
- bar: test4
foo: test3
name: foo

代替:

hello: world
my_list:
- bar: test2
foo: test
- bar: test4
foo: test3
name: foo

如何以这种方式缩进 my_list 元素?

最佳答案

This ticket建议当前的实现正确地遵循 the spec :

The “-”, “?” and “:” characters used to denote block collection entries are perceived by people to be part of the indentation. This is handled on a case-by-case basis by the relevant productions.

在同一个线程上,还有this code snippet (修改以适合您的示例)以获得您正在寻找的行为:

import yaml

class MyDumper(yaml.Dumper):

def increase_indent(self, flow=False, indentless=False):
return super(MyDumper, self).increase_indent(flow, False)

foo = {
'name': 'foo',
'my_list': [
{'foo': 'test', 'bar': 'test2'},
{'foo': 'test3', 'bar': 'test4'}],
'hello': 'world',
}

print yaml.dump(foo, Dumper=MyDumper, default_flow_style=False)

关于python yaml.dump 缩进错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25108581/

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