OrderedDict 的 (Im) 可变性
(Im)mutability of OrderedDict
Python 的 OrderedDict
数据结构是可变集合吗?
documentation没有说什么,在网上快速搜索后,我还没有找到任何答案。
Since OrderedDict is a mutable data structure, you can perform
mutating operations on its instances. You can insert new items, update
and remove existing items, and so on. If you insert a new item into an
existing ordered dictionary, then the item is added to the end of the
dictionary:
他们提供了几个 mutable 操作的例子,比如 insert:
>>> from collections import OrderedDict
>>> numbers = OrderedDict(one=1, two=2, three=3)
>>> numbers
OrderedDict([('one', 1), ('two', 2), ('three', 3)])
>>> numbers["four"] = 4
>>> numbers
OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4)])
一般来说,如果数据类型支持以下operations,则它被认为是可变序列类型。
OrderedDict 是可变的:
from collections import OrderedDict
d = OrderedDict.fromkeys('abcde')
d['a']= 'aretor'
print(d)
>> OrderedDict([('a', 'aretor'), ('b', None), ('c', None), ('d', None), ('e', None)])
print(d['a'])
>> aretor
The documentation does not say anything about it, and after a quick
search on the web, I have not found any answer yet.
当对 class 的可变性有疑问时,您可以 运行 在测试
之后
from collections import OrderedDict
from collections.abc import MutableSequence, MutableSet, MutableMapping
print(issubclass(OrderedDict,(MutableSequence,MutableSet,MutableMapping)))
输出
True
请参阅 collections.abc
文档中的 Collections Abstract Base Classes 以了解可以通过这种方式检查的其他内容。
Python 的 OrderedDict
数据结构是可变集合吗?
documentation没有说什么,在网上快速搜索后,我还没有找到任何答案。
Since OrderedDict is a mutable data structure, you can perform mutating operations on its instances. You can insert new items, update and remove existing items, and so on. If you insert a new item into an existing ordered dictionary, then the item is added to the end of the dictionary:
他们提供了几个 mutable 操作的例子,比如 insert:
>>> from collections import OrderedDict
>>> numbers = OrderedDict(one=1, two=2, three=3)
>>> numbers
OrderedDict([('one', 1), ('two', 2), ('three', 3)])
>>> numbers["four"] = 4
>>> numbers
OrderedDict([('one', 1), ('two', 2), ('three', 3), ('four', 4)])
一般来说,如果数据类型支持以下operations,则它被认为是可变序列类型。
OrderedDict 是可变的:
from collections import OrderedDict
d = OrderedDict.fromkeys('abcde')
d['a']= 'aretor'
print(d)
>> OrderedDict([('a', 'aretor'), ('b', None), ('c', None), ('d', None), ('e', None)])
print(d['a'])
>> aretor
The documentation does not say anything about it, and after a quick search on the web, I have not found any answer yet.
当对 class 的可变性有疑问时,您可以 运行 在测试
之后from collections import OrderedDict
from collections.abc import MutableSequence, MutableSet, MutableMapping
print(issubclass(OrderedDict,(MutableSequence,MutableSet,MutableMapping)))
输出
True
请参阅 collections.abc
文档中的 Collections Abstract Base Classes 以了解可以通过这种方式检查的其他内容。