← 中文资源

简体中文版本

OrderedDict.move_to_end 重排热键

OrderedDict.move_to_end 在命中时把键移到末尾,popitem(last=False) 从最旧一端弹出:容量受限时淘汰的恰好是最久未用项。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

after warmup  : ['a.conf', 'b.conf', 'c.conf']
after revisit : ['b.conf', 'c.conf', 'a.conf']
evicted: b.conf
after overflow: ['c.conf', 'a.conf', 'd.conf']

实现说明

全部逻辑都在函数 touch中。

使用要点

  • 跑完文件,输出里会留下标记——evicted:、after revisit :、after overflow:。
  • 调用方只需要 touch——其余都是内部实现。

常见问题

包管理器会看到什么?

一份空的依赖清单。示例没有需要抓取的导入。 文件在加载时定义 touch。

主要签名是 def touch(path)

核心语句

def touch(path):
    # 命中即移到末尾:迭代顺序 = 最近使用顺序
    if path in recent:
        recent.move_to_end(path)
    recent[path] = len(recent)
    # 超容量:从最旧的一端弹出 (evict oldest)
    if len(recent) > CAPACITY:
        evicted, _ = recent.popitem(last=False)
        print('evicted:', evicted)

代码示例

from collections import OrderedDict

CAPACITY = 3
recent = OrderedDict()


def touch(path):
    # 命中即移到末尾:迭代顺序 = 最近使用顺序
    if path in recent:
        recent.move_to_end(path)
    recent[path] = len(recent)
    # 超容量:从最旧的一端弹出 (evict oldest)
    if len(recent) > CAPACITY:
        evicted, _ = recent.popitem(last=False)
        print('evicted:', evicted)


touch('a.conf')
touch('b.conf')
touch('c.conf')
print('after warmup  :', list(recent))

touch('a.conf')  # 旧条目被重用,重新变成最新
print('after revisit :', list(recent))

touch('d.conf')  # 此时最旧的是 b.conf,而不是 a.conf
print('after overflow:', list(recent))