← 中文资源

简体中文版本

deque.rotate 实现轮询选择

选中队首后 rotate(-1) 一步把它转去队尾,有序端点表就变成公平的轮询器;转满一圈顺序复原,rotate(1) 反向一格,全程原地操作不产生新列表。

阅读英文原文

运行结果

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

turn 0: api-1
turn 1: api-2
turn 2: api-3
turn 3: api-1
turn 4: api-2
turn 5: api-3
cycle restored: True
after rotate(1): ['api-3', 'api-1', 'api-2']

机制说明

next_endpoint 读取 endpoints[0] 后调用 rotate(-1),一步把选中的队首转去队尾。六轮打印 api-1、api-2、api-3 两遍——固定列表变成公平的轮询器,无需任何重排代码。

六次选取(3 的倍数)后列表顺序复原,cycle restored 打印 True;rotate(1) 反向转一格,列表向另一侧移动一步。

注意事项

  • rotate 是 O(k) 的原地操作,不重建 deque。
  • 负数向左转;正数向右转。

核心语句

endpoints.rotate(-1)

代码示例

from collections import deque

endpoints = deque(["api-1", "api-2", "api-3"])

def next_endpoint() -> str:
    # Round-robin pick: read the head, then rotate one step left so it queues at the tail
    chosen = endpoints[0]
    endpoints.rotate(-1)
    return chosen

for turn in range(6):
    print(f"turn {turn}: {next_endpoint()}")

# After 6 picks (a multiple of 3) the order is restored; rotate(1) turns the other way
print("cycle restored:", list(endpoints) == ["api-1", "api-2", "api-3"])
endpoints.rotate(1)
print("after rotate(1):", list(endpoints))