python yaml.dump 缩进错误

python yaml.dump bad indentation(python yaml.dump 缩进错误)
本文介绍了python yaml.dump 缩进错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在执行以下 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)

这篇关于python yaml.dump 缩进错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I make a list of all members in a discord server using discord.py?(如何使用 discord.py 列出不和谐服务器中的所有成员?)
how to change discord.py bot activity(如何更改 discord.py 机器人活动)
Issues with getting VoiceChannel.members and Guild.members to return a full list(让 VoiceChannel.members 和 Guild.members 返回完整列表的问题)
Add button components to a message (discord.py)(将按钮组件添加到消息(discord.py))
on_message() and @bot.command issue(on_message() 和@bot.command 问题)
How to edit a message in discord.py(如何在 discord.py 中编辑消息)