python yaml.dump 缩进错误
- 作者: 抠脚大汉22285557
- 来源: 51数据库
- 2023-01-15
问题描述
我正在执行以下 python 代码:
I'm executing the following python code:
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 元素?
How can I indent the my_list elements this way?
推荐答案
这张票 表明当前的实现正确地遵循了规范:
This ticket suggests the current implementation correctly follows 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.
在同一个线程上,还有 此代码片段(已修改以适合您的示例)以获得您正在寻找的行为:
On the same thread, there is also this code snippet (modified to fit your example) to get the behavior you are looking for:
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)
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0
