python - 就地分配后保留 CommentedSeq flow_style

标签 python yaml ruamel.yaml

我想为 CommentedSeq 对象分配新值以保留其流程样式。然而,这样的操作会导致 TypeError: '<' not supported between instances of 'slice' and 'int'

这是否意味着 CommentedSeq 不支持就地赋值(Python 列表的最基本功能)?

from ruamel.yaml import YAML

y = YAML()
x = y.seq([1, 2])
x.fa.set_flow_style()
x[:] = [3, 4]


    451         # type: (Any, Any) -> None
    452         # try to preserve the scalarstring type if setting an existing key to a new value
--> 453         if idx < len(self):
    454             if isinstance(value, string_types) and \
    455                not isinstance(value, ScalarString) and \

TypeError: '<' not supported between instances of 'slice' and 'int'

最佳答案

您未能指出您一直在使用的 ruamel.yaml 的(过时)版本,也未能给出您不使用最新版本的原因。

CommentedSeq 不是列表或其子类,它是 MutableSequence 的子类(来自 collections.abc),尽管无论如何,我不会将就地切片分配称为 Python 列表的最基本功能,它当然不是 MutableSequences 支持的东西。

但这并不意味着CommentedSeq不支持就地[切片]分配:

$ mktmpenv -p /opt/python/3.6/bin/python
Running virtualenv with interpreter /opt/python/3.6/bin/python
Using base prefix '/opt/python/3.6'
New python executable in /home/venv/tmp-2aaa383875f076d7/bin/python
Installing setuptools, pip, wheel...done.
This is a temporary environment. It will be deleted when you run 'deactivate'.
(tmp-2aaa383875f076d7) $ pip install ruamel.yaml
Looking in indexes: https://pypi.org/simple, http://localhost:4040/anthon/dev/+simple/
Collecting ruamel.yaml
  Downloading https://files.pythonhosted.org/packages/77/51/f4314ebd8a3ec4989a3b3339a47382d87f251e5b82f2b7852a67649bc862/ruamel.yaml-0.15.64-cp36-cp36m-manylinux1_x86_64.whl (645kB)
    100% |████████████████████████████████| 655kB 3.5MB/s 
Installing collected packages: ruamel.yaml
Successfully installed ruamel.yaml-0.15.64
(tmp-2aaa383875f076d7) $ python
Python 3.6.6 (default, Jul 28 2018, 11:00:00) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from ruamel.yaml import YAML
>>> 
>>> y = YAML()
>>> x = y.seq([1, 2])
>>> x.fa.set_flow_style()
>>> x[:] = [3, 4]
>>> print(x)
[3, 4]
>>> import sys
>>> y.dump(x, sys.stdout)
[3, 4]

关于python - 就地分配后保留 CommentedSeq flow_style,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52131767/

相关文章:

python - 根据最后一次出现的分隔符将字符串拆分为 2

java - 使用 dropwizard 时 config.yml 为 "maxFileSize must be specified"

python - Yaml 转储程序从 None 值输出空白而不是 null。如何让它输出 null 呢?

python - 基于堆栈的修改前序树遍历

python - 从 RGB 转换为 LAB 色彩空间——是否了解 L*A*B* 值的范围?

java - 无法将 yaml 字符串转换为在 Java 中使用键 "NO"进行映射

mysql - 加载database.yml出现错误

python - 使用 ruamel 保持 YAML 文件顺序

python-3.x - 使用 yaml.dump 时如何去掉字符串中的引号

python - 如何使用python将数据写入excel