gpt4 book ai didi

python - 就地分配后保留 CommentedSeq flow_style

转载 作者:行者123 更新时间:2023-12-01 09:05:03 24 4
gpt4 key购买 nike

我想为 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/

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