替换 OrderedDict 中的元素?
Replacing an element in an OrderedDict?
我应该删除索引处的项目并在索引处添加项目吗?
我应该去哪里寻找 OrderedDict
class 的来源?
来自 Python 文档:
If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.
如果值已经存在,OrderedDict
使用值的位置; 如果不是,就把它当成一个新值加到最后。
这是in the documentation。如果您需要替换并维持秩序,则必须手动执行:
od = OrderedDict({i:i for i in range(4)})
# od = OrderedDict([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)])
# Replace the key and value for key == 0:
d = OrderedDict(('replace','key') if key == 0 else (key, value) for key, value in od.items())
# d = OrderedDict([('replace', 'key'), (1, 1), (2, 2), (3, 3), (4, 4)])
# Single value replaces are done easily:
d[1] = 20 # and so on..
此外,在文档页面的顶部,您会看到对文件的引用,其中包含 OrderedDict
class 的源代码。它在 collections.py
and, actually, the first class defined.
我应该删除索引处的项目并在索引处添加项目吗?
我应该去哪里寻找 OrderedDict
class 的来源?
来自 Python 文档:
If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.
如果值已经存在,OrderedDict
使用值的位置; 如果不是,就把它当成一个新值加到最后。
这是in the documentation。如果您需要替换并维持秩序,则必须手动执行:
od = OrderedDict({i:i for i in range(4)})
# od = OrderedDict([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)])
# Replace the key and value for key == 0:
d = OrderedDict(('replace','key') if key == 0 else (key, value) for key, value in od.items())
# d = OrderedDict([('replace', 'key'), (1, 1), (2, 2), (3, 3), (4, 4)])
# Single value replaces are done easily:
d[1] = 20 # and so on..
此外,在文档页面的顶部,您会看到对文件的引用,其中包含 OrderedDict
class 的源代码。它在 collections.py
and, actually, the first class defined.